解决Spring|解决Spring Security的权限配置不生效问题
目录
- SpringSecurity权限配置不生效
- 1、不生效的例子
- 2、解决办法
- SpringSecurity动态配置权限
- 导入依赖
- 相关配置
- 创建UserMapper类&&UserMapper.xml
- 创建UserServiceMenuService
- 创建CustomFilterInvocationSecurityMetadataSource
- 创建CustomAccessDecisionManager
- 创建WebSecurityConfig配置类
Spring Security权限配置不生效 在集成Spring Security做接口权限配置时,在给用户配置的权限后,还是一直显示“无权限”或者"权限不足"。
1、不生效的例子
接口
@RequestMapping("/admin")@ResponseBody@PreAuthorize("hasRole('ADMIN')")public String printAdmin() {return "如果你看见这句话,说明你有ROLE_ADMIN角色"; }@RequestMapping("/user")@ResponseBody@PreAuthorize("hasRole('USER')")public String printUser() {return "如果你看见这句话,说明你有ROLE_USER角色"; }
SecurityConfig
.and().authorizeRequests().antMatchers("/user").hasAnyRole("USER") .antMatchers("/admin").hasAnyRole("ADMIN").anyRequest().authenticated() //必须授权才能范围
用户携带权限
文章图片
2、解决办法
经测试,只有用户携带权限的字段为 “ROLE_” + 接口/配置 中的权限字段,才能控制生效,举例:
将上面的用户携带权限改为
文章图片
Spring Security动态配置权限
导入依赖
org.springframework.boot spring-boot-starter-securityorg.springframework.boot spring-boot-starter-weborg.mybatis.spring.boot mybatis-spring-boot-starter2.1.3 com.alibaba druid-spring-boot-starter1.1.22 mysql mysql-connector-javaruntime5.1.46 org.springframework.boot spring-boot-starter-testtestorg.junit.vintage junit-vintage-engineorg.springframework.security spring-security-testtest
文章图片
相关配置
application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/javaboy?useUnicode=true&characterEncoding=utf8&serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=rootspring.datasource.type=com.alibaba.druid.pool.DruidDataSource
实体类User,Role,Menu
这里要实现UserDetails接口,这个接口好比一个规范。防止开发者定义的密码变量名各不相同,从而导致springSecurity不知道哪个方法是你的密码
public class User implements UserDetails {private Integer id; private String username; private String password; private Boolean enabled; private Boolean locked; private ListroleList; @Overridepublic Collection extends GrantedAuthority> getAuthorities() {List authorities = new ArrayList<>(); for (Role role : roleList) {authorities.add(new SimpleGrantedAuthority(role.getName())); }return authorities; }@Overridepublic String getPassword() {return password; }@Overridepublic String getUsername() {return username; }@Overridepublic boolean isAccountNonExpired() {return true; }@Overridepublic boolean isAccountNonLocked() {return !locked; }@Overridepublic boolean isCredentialsNonExpired() {return true; }@Overridepublic boolean isEnabled() {return enabled; }public Integer getId() {return id; }public void setId(Integer id) {this.id = id; }public void setUsername(String username) {this.username = username; }public void setPassword(String password) {this.password = password; }public Boolean getEnabled() {return enabled; }public void setEnabled(Boolean enabled) {this.enabled = enabled; }public Boolean getLocked() {return locked; }public void setLocked(Boolean locked) {this.locked = locked; }public List getRoleList() {return roleList; }public void setRoleList(List roleList) {this.roleList = roleList; }}
public class Role {private Integer id; private String name; private String nameZh; ...}
public class Menu {private Integer id; private String pattern; private Listroles; ...}
创建UserMapper类&&UserMapper.xml
和MenuMapper类&&MenuMapperxml
UserMapper
@Mapperpublic interface UserMapper {User getUserByName(String name); ListgetRoleById(Integer id); }
UserMapper.xml
select * from user where username= #{name}select * from role where id in (select rid from user_role where uid = #{uid})
MenuMapper
@Mapperpublic interface MenuMapper {List
MemuMapper.xml
select m.*,r.id as rid,r.name as rname,r.nameZh as rnameZh from menu_role mr left joinmenu m on mr.mid = m.id left join role r on mr.rid = r.id
文章图片
创建UserService MenuService
创建UserService实现UserServiceDetails接口
@Servicepublic class UserService implements UserDetailsService {@Autowiredprivate UserMapper userMapper; @Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userMapper.getUserByName(username); if(user ==null){throw new UsernameNotFoundException("用户名不存在"); }user.setRoleList(userMapper.getRoleById(user.getId())); return user; }}
创建MenuService
@Servicepublic class MenuService {@Autowiredprivate MenuMapper menuMapper; public List
创建CustomFilterInvocationSecurityMetadataSource
实现接口FilterInvocationSecurityMetadataSource
注:加@comppent注解,把自定义类注册成spring组件
supports返回值设成true表示支持
重写getAttributes()方法
invacation
调用 ,求助metadata
元数据
@Componentpublic class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {//ant风格的路径匹配器AntPathMatcher pathMatcher = new AntPathMatcher(); @Autowiredprivate MenuService menuService; //supports返回值设成true表示支持@Overridepublic boolean supports(Class> aClass) {return true; }@Overridepublic CollectiongetAttributes(Object object) throws IllegalArgumentException {//获取当前用户请求的urlString requestUrl=((FilterInvocation) object).getRequestUrl(); //数据库中查询出所有的路径List
创建CustomAccessDecisionManager
实现AccessDecisionManager接口 access 通道
注:加@comppent注解,把自定义类注册成spring组件
将两个supports()都设置成true
重写decide()方法
@Componentpublic class CustomAccessDecisionManager implements AccessDecisionManager {@Overridepublic void decide(Authentication authentication, Object o, Collectioncollection) throws AccessDeniedException, InsufficientAuthenticationException {//configattributes里存放着CustomFilterInvocationSecurityMetadataSource过滤出来的角色for (ConfigAttribute configAttribute : collection) {//如果你请求的url在数据库中不具备角色if ("ROLE_def".equals(configAttribute.getAttribute())) {//在判断是不是匿名用户(也就是未登录)if (authentication instanceof AnonymousAuthenticationToken) {System.out.println(">>>>>>>>>>>>>>>>匿名用户>>>>>>>>>>>>>>"); throw new AccessDeniedException("权限不足,无法访问"); }else{//这里面就是已经登录的其他类型用户,直接放行System.out.println(">>>>>>>>>>>其他类型用户>>>>>>>>>>>"); return; }}//如果你访问的路径在数据库中具有角色就会来到这里//Autherntication这里面存放着登录后的用户所有信息Collection extends GrantedAuthority> authorities = authentication.getAuthorities(); for (GrantedAuthority authority : authorities) {System.out.println(">>>>>>>authority(账户所拥有的权限):"+authority.getAuthority()); System.out.println(">>>>>>>configAttribute(路径需要的角色):"+configAttribute.getAttribute()); //路径需要的角色和账户所拥有的角色作比较if (authority.getAuthority().equals(configAttribute.getAttribute())) {System.out.println(">>>>>>>>>>>>>>>>>>进来>>>>>>>>>>>>>>>>>"); return; }}}}@Overridepublic boolean supports(ConfigAttribute configAttribute) {return true; }@Overridepublic boolean supports(Class> aClass) {return true; }}
创建WebSecurityConfig配置类
WebSecurityConfig实现WebSecurityConfigurerAdapter
注入一会所需要的类
SpringSecurity5.0之后必须密码加密
将数据库查出的账户密码交给SpringSecurity去判断
配置HttpSecurity
@Configurationpublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserService userService; @Autowiredprivate CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource; @Autowiredprivate CustomAccessDecisionManager customAccessDecisionManager; //springSecutity5.0之后必密码加密@BeanPasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder(); }//将数据库查出的账户密码交给springsecurity去判断@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userService); }//配置HttpSecurity@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().withObjectPostProcessor(new ObjectPostProcessor() {@Overridepublic O postProcess(O object){object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource); object.setAccessDecisionManager(customAccessDecisionManager); return object; }}).and().formLogin().permitAll().and().csrf().disable(); }}
Controller
@RestControllerpublic class HelloController {@GetMapping("/hello")public String hello(){return "hello"; }@GetMapping("/dba/hello")public String dba(){return "hello dba"; }@GetMapping("/admin/hello")public String admin(){return "hello admin"; }@GetMapping("/user/hello")public String user(){return "hello user"; }}
文章图片
文章图片
【解决Spring|解决Spring Security的权限配置不生效问题】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
推荐阅读
- 使用SpringSecurity设置角色和权限的注意点
- 移动端输入框被挤出视口的解决方案
- Python3|解决Python代码编码问题 SyntaxError: Non-UTF-8 code starting with '\xc1'
- 项目实战|SpringBoot个人博客从无到有项目搭建——实战综合介绍
- springboot启动前执行方法的四种方式总结
- 基于spring注入为null的原因及解决方案
- JPA|JPA @Query时,无法使用limit函数的问题及解决
- 关于@Query注解的用法(Spring|关于@Query注解的用法(Spring Data JPA)
- SpringBoot|SpringBoot JPA出现错误:No identifier specified for en解决方案
- 使用|使用 SAP BTP 创建一个 Spring Boot Java 应用