首頁>技術>

需要,基於RBAC的許可權訪問,採用SpringSecurity安全管理框架+SpringBoot+Mybatis資料庫持久框架。

資料庫設計:

user使用者名稱:ennabled,accountNonExpired,accountNonLocked,CredentialsNonExpired預設為1

role角色表:

permission許可權表:

user_role 使用者-角色中間表:

role_permission色色-許可權中間表:

permission表中初始資料,許可權名為permTag

編碼實現:

1.pom.xml,引入了jdbc,thymeleaf,security,web,mybatis,devtools,lombox,mysql

#資料庫連線,暫時未使用資料庫連線池spring.datasource.url=jdbc:mysql://localhost:3306/yderpspring.datasource.username=rootspring.datasource.password=a61322799#開發期間不需要快取模板spring.thymeleaf.cache=false

3.資原始檔,其中main.html為需要許可權才能訪問的頁面

reg.html

<form action="/reg" method="post">    使用者名稱<input type="text" name="username"/> <br/>    使用者名稱<input type="text" name="realname"/> <br/>    密碼 <input type="password" name="password"/><br/>    <input type="submit" value="註冊"></form>

login.html

//角色實現UserDetails介面實現使用者的封裝@Datapublic class User  implements UserDetails {    private int id;    private String username;    private String realname;    private String password;    private LocalDate createDate;    private LocalDateTime lastLoginTime;    //賬戶是否不可用,資料庫為1代表true,0代表false,預設為1    private boolean enabled;    //賬戶是否未過期    private boolean accountNonExpired;    //賬戶是否鎖定    private boolean accountNonLocked;    //密碼是否未過期    private boolean credentialsNonExpired;    //許可權集合    private List<GrantedAuthority>  authorities;} @Datapublic class Role {    private int id;    private String roleName;    private String roleDesc;} @Datapublic class Permission {    private int id;    private String permName;    //許可權標誌符,authorities集合的值    private String permTag;}

5.資料庫查詢dao介面

@Mapper@Componentpublic interface UserDao {    //使用者名稱查詢使用者資訊    @Select("select * from user where userName = #{userName}")    public User selectByUserName(String userName);    //使用者名稱查詢當前使用者的許可權資訊    @Select("select permission.* FROM" +            "    user  u" +            "    INNER JOIN user_role ON u.id = user_role.uid" +            "    INNER JOIN role_permission on user_role.rid = role_permission.rid" +            "    INNER JOIN permission on role_permission.pid = permission.id" +            "    WHERE u.username = #{userName};")    public List<Permission> findPermissionByUserName(String userName);    //註冊使用者    @Insert("insert into user values(default,#{user.username}," +            "#{user.realname},#{user.password},now(),now(),default,default,default,default)")    int insert(@Param("user") User user);}

6.UserService

public interface UserService {    public int insert(User user);} @Servicepublic class UserServiceImpl implements UserService {    @Autowired    private UserDao userDao =null;    @Override    public int insert(User user) {        return userDao.insert(user);    }}

7.MyController註冊

@Controllerpublic class MyController {    @Autowired    UserService userService = null;    //使用者註冊    @RequestMapping("/reg")    @ResponseBody    public String reg(User user){        System.out.println(user);        String pwd = user.getPassword();        //加密,springSecurity現在預設要強制加密        pwd = new BCryptPasswordEncoder().encode(pwd);         user.setPassword(pwd);        int insert = userService.insert(user);        if(insert > 0){            return "註冊成功";        }        return "註冊失敗";     }}

8.springMVC config配置

@Configurationpublic class MyConfig implements WebMvcConfigurer {   //靜態資源URI和位置對映    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("/static/**")                .addResourceLocations("classpath:/static/");    }    //檢視對映    @Override    public void addViewControllers(ViewControllerRegistry registry) {        registry.addViewController("/login").setViewName("login");        registry.addViewController("/").setViewName("index");        registry.addViewController("/403").setViewName("403");        registry.addViewController("/main").setViewName("main");    }}

9.許可權不足邏輯跳轉

@Configurationpublic class ErrorPageConfig implements ErrorPageRegistrar  {    @Override    public void registerErrorPages(ErrorPageRegistry registry) {        //許可權不足的頁面導向        ErrorPage error403 = new ErrorPage(HttpStatus.FORBIDDEN,"/403");        registry.addErrorPages(error403);    }}

10.UserDetailsService介面的實現

@Servicepublic class MyUserDetalisService implements UserDetailsService {    @Autowired    UserDao userDao = null;     @Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {        //查詢當前使用者資訊        User user = userDao.selectByUserName(username);        //查詢當前使用者許可權        List<Permission> list = userDao.findPermissionByUserName(username);        List<GrantedAuthority> authorities = new ArrayList<>();        /*        * 將getPermTag()構建一個GrantedAuthority介面例項物件,放於List<GrantedAuthority>中        * */        list.forEach(l ->{            authorities.add(new SimpleGrantedAuthority(l.getPermTag()));        });        //使用者資訊設定許可權集合        user.setAuthorities(authorities);        return user;    }}

11.springSecurity配置,重點

@EnableWebSecuritypublic class MySecurity extends WebSecurityConfigurerAdapter {    @Autowired    MyUserDetalisService myUserDetalisService = null;     //http安全配置    @Override    protected void configure(HttpSecurity http) throws Exception {        http.authorizeRequests()  //所有請求攔截         .antMatchers("/static/**").permitAll() //放在所有攔截的前面放行不需要攔截的資源         .antMatchers("/login").permitAll()  //放行登入         .antMatchers("/logout").permitAll() //放行登出         .antMatchers("/reg").permitAll()  //放行註冊         .antMatchers("/main").hasAnyAuthority("ROLE_PRODUCT_LIST")//此頁需要許可權         .anyRequest().authenticated() //除上所有攔截需要使用者認證             .and()                .formLogin().loginPage("/login") //forlogin認證                .failureUrl("/login?error=true")//登陸錯誤頁            .and()                .csrf().disable(); //關閉csrf校驗     }    //認證管理器配置    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception {        auth.userDetailsService(myUserDetalisService)                //查詢時需要密碼加密後和資料庫做比較                .passwordEncoder(new BCryptPasswordEncoder());    }}

8
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 學習VB程式設計第91天 MySQL資料庫增刪改查