Spring Security - 权限与角色
配置类:
/* * Security配置类 * 要实现WebSecurityConfigurerAdapter抽象类 * */ @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { //用户Service,根据前端用户名从数据库中查询用户信息 @Autowired UserDetailsService userDetailsService; //加密方式 @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } //配置 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //配置接口与加密方式 auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } //配置登录访问的接口 @Override protected void configure(HttpSecurity http) throws Exception { /*1.关于登录*/ http.formLogin() //设置登录页面 .loginPage("/login.html") //设置登录接口 .loginProcessingUrl("/user/login") //设置登录之后跳转 .defaultSuccessUrl("/success"); /*2.关于拦截*/ http.authorizeRequests() //设置不登陆时就可以访问的页面 .antMatchers("/","/user/login").permitAll() //全部可以访问 一般不使用 .anyRequest().authenticated() .and().csrf().disable(); //关闭csrf防护 /*3.关于权限*/ http.authorizeRequests() //单个权限 .antMatchers("/adminManager/").hasAuthority("admin") //多个权限(只要有一个权限就可以访问) .antMatchers("/adminManager/").hasAnyAuthority("admin,root"); /*4.关于角色*/ http.authorizeRequests() //单个角色 .antMatchers("/role/").hasRole("role1") //多个角色(只要有一个角色就可以访问) .antMatchers("/role/").hasAnyRole("role1,role2"); } }
LeUser:
@Data public class LeUser { private String userId; private String userName; private String userPassword; private LeRole leRole; private LeAuthority leAuthority; }
LeRole:
@Data public class LeRole { private String roleId; private String roleName; public String getRoleName(){ return "ROLE_"+roleName; } }
LeAuthority:
@Data public class LeAuthority { private String authorityId; private String authorityName; }
LeUserDetails:
@Data //重写UserDetails public class LeUserDetails implements UserDetails, Serializable { //自定义的user类 private LeUser leUser; public LeUserDetails(LeUser leUser) { this.leUser = leUser; } //权限 @Override public Collection<? extends GrantedAuthority> getAuthorities() { //权限 String authority=leUser.getLeAuthority().getAuthorityName(); //角色 String role=leUser.getLeRole().getRoleName(); String authorityString=authority+","+role; return AuthorityUtils.commaSeparatedStringToAuthorityList(authorityString); } //用户密码 @Override public String getPassword() { return leUser.getUserPassword(); } //用户名称 @Override public String getUsername() { return leUser.getUserName(); } //账号是否未过期 @Override public boolean isAccountNonExpired() { return true; } //账号是否未锁定 @Override public boolean isAccountNonLocked() { return true; } //密码是否未过期 @Override public boolean isCredentialsNonExpired() { return true; } //是否激活 @Override public boolean isEnabled() { return true; } }