springboot研究四:springboot + security + easyui + mysql实现权限控制

最近做项目,研究了一下springboot权限控制,采用security,前端采用easy,看一下页面:用户xiaoming登陆:

springboot研究四:springboot + security + easyui + mysql实现权限控制_第1张图片

用户xiaoming1登陆:

springboot研究四:springboot + security + easyui + mysql实现权限控制_第2张图片

2个用户登陆后,拥有不一样的菜单权限。

整个系统框架采用:springboot+mybatis+mysql+springsecurity,前台采用easyui

WebConfig.java类,这个类配置了登录页面

 

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Resource
    private AsyncHandlerInterceptor loginInterceptor;

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
    }

}

 

SecurityConfig类,配置了资源的权限配置,静态资源允许所有请求访问

 

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().
                antMatchers("/boot/static/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .permitAll()
                .and()
                .logout().permitAll(); //注销行为任意访问
        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        // 验证码拦截器,配置到UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class).formLogin();
    }
}

说明一下:ValidateCodeFilter 暂时没有用,准备登录页面加验证码的时候用。

 
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().
                antMatchers("/boot/static/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .permitAll()
                .and()
                .logout().permitAll(); //注销行为任意访问
        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        // 验证码拦截器,配置到UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class).formLogin();
    }
}

UserServiceImpl 类,loadUserByUsername方法验证用户登陆

@Service("userService")
public class UserServiceImpl implements UserDetailsService {
    @Resource
    private RoleDao roleDao;
    @Resource
    private UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户
        if(username == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List authorities = new ArrayList<>();
        User user = userDao.getUserbyName(username);
        List roles = roleDao.getRolebyUserId(user.getId());
        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        for(Role role:roles)
        {
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return new org.springframework.security.core.userdetails.User("xiaoming",user.getPassword(), authorities);
    }
}

LoginInterceptor类,

response.setHeader("X-Frame-Options", "SAMEORIGIN");这段代码是为了解决easyui tabs不能显示页面的问题。
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        return true;
    }
}


下面看一下登陆页面:

 




    
    Validate Form on Submit - jQuery EasyUI Demo
    
    
    
    
    
    


欢迎登录boot系统

用户名或密码错误

再看下主页面:





Template
















LoginController类,实现登陆成功后页面跳转:

@Controller
public class LoginController {
	private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
	@GetMapping("/")
	public String login(){
		logger.info("登录成功,跳转主页面");
		return "index";
	}
}

UserController类,菜单类

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/list")
    public String toUserManage(){
        return "user/userList";
    }
}

数据库设计:

db_user表

CREATE TABLE `db_user` (                               
           `id` bigint(20) NOT NULL AUTO_INCREMENT,             
           `username` varchar(100) NOT NULL,                    
           `password` varchar(100) NOT NULL,                    
           PRIMARY KEY (`id`)                                   
         ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 
insert into db_user values(1,'xiaoming','$2a$10$LpzLqSAVaWZadH2N8P319u0jz4bcWCOCib9Ngt6EDGTRfNncehKMi');
insert into db_user values(1,'xiaoming1','$2a$10$LpzLqSAVaWZadH2N8P319u0jz4bcWCOCib9Ngt6EDGTRfNncehKMi');


db_role表

CREATE TABLE `db_role` (                               
           `id` bigint(20) NOT NULL AUTO_INCREMENT,             
           `name` varchar(100) NOT NULL,                        
           PRIMARY KEY (`id`)                                   
         ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8  
insert into db_role value(1,'ROLE_ADMIN');
insert into db_role value(2,'ROLE_USER');

db_user_role表

CREATE TABLE `db_user_role` (                          
                `id` bigint(20) NOT NULL AUTO_INCREMENT,             
                `role_id` bigint(20) NOT NULL,                       
                `user_id` bigint(20) NOT NULL,                       
                PRIMARY KEY (`id`)                                   
              ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8  
insert into db_user_role values(1,1,1)
insert into db_user_role values(2,2,1)
insert into db_user_role values(3,1,2)


不多粘贴代码了,源码地址

https://github.com/jinjunzhu/springboot.git

参考:

https://www.cnblogs.com/softidea/p/7068149.html

数据库表:db_role

CREATE TABLE `db_role` (                               
           `id` bigint(20) NOT NULL AUTO_INCREMENT,             
           `name` varchar(20) NOT NULL,                         
           PRIMARY KEY (`id`)                                   

         ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 

insert into db_role values(1,'ROLE_ADMIN');
insert into db_role values(1,'ROLE_USER');

数据库表 :db_user

CREATE TABLE `db_user` (                               
           `id` bigint(20) NOT NULL AUTO_INCREMENT,             
           `username` varchar(100) NOT NULL,                    
           `password` varchar(100) NOT NULL,                    
           PRIMARY KEY (`id`)                                   

         ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 

insert into db_user values(1,'xiaoming','$2a$10$QOT0aqz0gjkmF/RwoH6GGuWG3JtPTnNd6hL.rliSNc8K7ysHMjcOm');
insert into db_user values(2,'xiaoming1','$2a$10$QOT0aqz0gjkmF/RwoH6GGuWG3JtPTnNd6hL.rliSNc8K7ysHMjcOm');

数据库表:db_user_role

CREATE TABLE `db_user_role` (                          
                `id` bigint(20) NOT NULL AUTO_INCREMENT,             
                `user_id` bigint(20) NOT NULL,                       
                `role_id` bigint(20) NOT NULL,                       
                PRIMARY KEY (`id`)                                   
              ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8  

insert into db_user_role values(1,1,1);
insert into db_user_role values(2,1,2);
insert into db_user_role values(3,2,2);

 

你可能感兴趣的:(个人开发,spring-boot)