解决Spring Security的权限配置不生效问题

 更新时间:2022年3月12日 22:44  点击:696 作者:varz

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动态配置权限

导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.22</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
    <version>5.1.46</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

相关配置

application.properties

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/javaboy?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.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 List<Role> roleList;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roleList) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }
    @Override
    public String getPassword() {
        return password;
    }
    @Override
    public String getUsername() {
        return username;
    }
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return !locked;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public 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<Role> getRoleList() {
        return roleList;
    }
    public void setRoleList(List<Role> 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 List<Role> roles;
...
}

创建UserMapper类&&UserMapper.xml

和MenuMapper类&&MenuMapperxml

UserMapper

@Mapper
public interface UserMapper {
    User getUserByName(String name);
    List<Role> getRoleById(Integer id);
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qwl.mysecuritydy.mapper.UserMapper">
    <select id="getUserByName" resultType="com.qwl.mysecuritydy.bean.User">
        select * from user where username= #{name}
    </select>
    <select id="getRoleById" resultType="com.qwl.mysecuritydy.bean.Role">
        select * from role where id in (select rid from user_role where uid = #{uid})
    </select>
</mapper>

MenuMapper

@Mapper
public interface MenuMapper {
    List<Menu> getMenus();
}

MemuMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qwl.mysecuritydy.mapper.MenuMapper">
    <resultMap id="menus_map" type="com.qwl.mysecuritydy.bean.Menu">
        <id property="id" column="id"/>
        <result property="pattern" column="pattern"/>
        <collection property="roles" ofType="com.qwl.mysecuritydy.bean.Role">
            <id property="id" column="rid"/>
            <result property="name" column="rname"/>
            <result property="nameZh" column="rnameZh"/>
        </collection>
    </resultMap>
    <select id="getMenus" resultMap="menus_map">
        select m.*,r.id as rid,r.name as rname,r.nameZh as rnameZh from menu_role mr left join
        menu m on mr.mid = m.id left join role r on mr.rid = r.id
    </select>
</mapper>

创建UserService MenuService

创建UserService实现UserServiceDetails接口

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public 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

@Service
public class MenuService {
    @Autowired
    private MenuMapper menuMapper;
    public List<Menu> getMenus() {return menuMapper.getMenus();}
}

创建CustomFilterInvocationSecurityMetadataSource

实现接口FilterInvocationSecurityMetadataSource

注:加@comppent注解,把自定义类注册成spring组件

supports返回值设成true表示支持

重写getAttributes()方法

  • invacation 调用 ,求助
  • metadata 元数据

@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    //ant风格的路径匹配器
    AntPathMatcher pathMatcher = new AntPathMatcher();
    @Autowired
    private MenuService menuService;
        //supports返回值设成true表示支持
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取当前用户请求的url
        String requestUrl=((FilterInvocation) object).getRequestUrl();
        //数据库中查询出所有的路径
        List<Menu> menus  =menuService.getMenus();
        for (Menu menu : menus) {
            //判断用户请求的url和数据库的url是否能匹配的上
            if (pathMatcher.match(menu.getPattern(), requestUrl)) {
                List<Role> roles =menu.getRoles();
                String[] roleStr = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    roleStr[i]=roles.get(i).getName();
                }
                //将筛选的url路径所具备的角色返回回去
                return SecurityConfig.createList(roleStr);
            }
        }
        //如果没有匹配上就返回一个默认的角色,作用好比作一个标记
        return SecurityConfig.createList("ROLE_def");
    }
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }
}

创建CustomAccessDecisionManager

实现AccessDecisionManager接口 access 通道

注:加@comppent注解,把自定义类注册成spring组件

将两个supports()都设置成true

重写decide()方法

@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) 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;
                }
            }
        }
    }
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}

创建WebSecurityConfig配置类

WebSecurityConfig实现WebSecurityConfigurerAdapter

注入一会所需要的类

SpringSecurity5.0之后必须密码加密

将数据库查出的账户密码交给SpringSecurity去判断

配置HttpSecurity

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;
    @Autowired
    private CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;
    @Autowired
    private CustomAccessDecisionManager customAccessDecisionManager;
    //springSecutity5.0之后必密码加密
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    //将数据库查出的账户密码交给springsecurity去判断
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }
    //配置HttpSecurity
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object){
                        object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
                        object.setAccessDecisionManager(customAccessDecisionManager);
                        return object;
                    }
                })
                .and()
                .formLogin()
                .permitAll()
                .and()
                .csrf().disable();
    }
}

Controller 

@RestController
public 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";
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。 

原文出处:https://blog.csdn.net/g_soledad/article/details/104042440

[!--infotagslink--]

相关文章

  • IntelliJ IDEA2021.1 配置大全(超详细教程)

    这篇文章主要介绍了IntelliJ IDEA2021.1 配置大全(超详细教程),需要的朋友可以参考下...2021-04-18
  • Windows VPN服务器配置图文教程 超详细版

    VPN可以虚拟出一个专用网络,让远处的计算机和你相当于处在同一个局域网中,而中间的数据也可以实现加密传输,用处很大,特别是在一些大公司,分公司处在不同的区域。...2016-01-27
  • Tomcat配置及如何在Eclipse中启动

    这篇文章主要介绍了Tomcat配置及如何在Eclipse中启动,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-02-04
  • Laravel4安装配置的方法

    如果我们需要安培Laravel4的话最php最低要求要在php5.3.7版本并且我们需要把mcrypt与openss这两个扩展开启才可以,具体步骤我们参考下文。 前面我们介绍我了 com...2016-11-25
  • Spring AOP 对象内部方法间的嵌套调用方式

    这篇文章主要介绍了Spring AOP 对象内部方法间的嵌套调用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-08-29
  • Spring Cloud 中@FeignClient注解中的contextId属性详解

    这篇文章主要介绍了Spring Cloud 中@FeignClient注解中的contextId属性详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-25
  • Springboot如何实现Web系统License授权认证

    这篇文章主要介绍了Springboot如何实现Web系统License授权认证,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-05-28
  • 详解Maven profile配置管理及激活profile的几种方式

    这篇文章主要介绍了详解Maven profile配置管理及激活profile的几种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-26
  • 如何在Spring WebFlux的任何地方获取Request对象

    这篇文章主要介绍了如何在Spring WebFlux的任何地方获取Request对象,帮助大家更好的理解和使用springboot框架,感兴趣的朋友可以了解下...2021-01-26
  • 详解SpringCloudGateway内存泄漏问题

    这篇文章主要介绍了详解SpringCloudGateway内存泄漏问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-07-16
  • IDEA如何添加配置文件到classpath中

    这篇文章主要介绍了IDEA如何添加配置文件到classpath中,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-19
  • 查找php配置文件php.ini所在路径的二种方法

    通常php.ini的位置在:复制代码 代码如下:/etc目录下或/usr/local/lib目录下。如果你还是找不到php.ini或者找到了php.ini修改后不生效(其实是没找对),请使用如下办法:1.新建php文件,写入如下代码复制代码 代码如下:<?phpe...2014-05-31
  • 部署PHP时的4个配置修改说明

    以下就是部署PHP时的4个配置修改说明,大家一个一个进行学习研究。1、short_open_tag 是什么呢? 决定是否允许使用代码开始标志的缩写形式(<&#63; &#63;> )。如果要和 XML 结合使用PHP,可以禁用此选项以便于嵌入使用<&#63;x...2015-10-21
  • Spring为什么不推荐使用@Autowired注解详析

    @Autowired 注解的主要功能就是完成自动注入,使用也非常简单,但这篇文章主要给大家介绍了关于Spring为什么不推荐使用@Autowired注解的相关资料,需要的朋友可以参考下...2021-11-03
  • Vue-Router的routes配置详解

    在使用vue-router的项目中,实例化VueRouter是其配置选项routes该选项指定路由与视图的组件的关系或者路由与其他路由的关系,Router配置选项中是其中最重要的配置。本文就详细的介绍一下...2021-10-25
  • 华为畅享20Pro配置怎么样?华为畅享20Pro参数配置分析

    华为畅享20Pro配置怎么样?对于即将上市的华为畅享20 Pro手机,很多的网友们也是相当关注的,大家都想要知道这款华为畅享20 Pro手机的配置到底怎么样,赶紧看看吧...2020-06-29
  • Springboot如何使用mybatis实现拦截SQL分页

    这篇文章主要介绍了Springboot使用mybatis实现拦截SQL分页,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-19
  • 浅谈关于如何检测iOS14本地网络权限的一些思路

    这篇文章主要介绍了浅谈关于如何检测iOS14本地网络权限的一些思路,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-08
  • phpMyadmin创建数据库和设置用户权限图解

    phpmyadmin是一款很不错的WEB对mysql数据库管理软件,如果你想创建数据库与设置用户权限我们必须操作用户的很高的权限,如ROOT权限,下面我来给大家介绍介绍。 先来配...2016-11-25
  • SpringMVC文件上传原理及实现过程解析

    这篇文章主要介绍了SpringMVC文件上传原理及实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-07-15