基于方法的权限管理实现
创始人
2025-05-30 10:52:50
0

实现步骤

  1. 实现UserDetails,重写getAuthorities方法。
    public class LoginUser implements UserDetails {/*** 角色集合*/private Set roles;@JSONField(serialize = false)private List authorities;@Overridepublic Collection getAuthorities() {if (Objects.nonNull(this.authorities)) {return this.authorities;}authorities = this.roles.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).collect(Collectors.toList());return authorities;}...
    }
    
  2. 在 SpringSecurity 的配置类上添加注解@EnableGlobalMethodSecurity
    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {...
    }
    
  3. 在需要权限管理的方法上添加注解PreAuthorize,本文使用@hasRole在方法访问前进行角色校验。
    @GetMapping("my_info")
    @PreAuthorize("hasRole('admin')")
    public Result getMyInfo() {User user = userService.getMyInfo();return Result.success(user);
    }
    

流程分析

  1. 进行角色校验时,进入到SecurityExpressionRoothasAnyAuthorityName方法中。
    在这里插入图片描述
  2. 使用getAuthoritySet方法获取当前身份验证信息的角色列表,主要代码如下。
    if (this.roles == null) {Collection userAuthorities = this.authentication.getAuthorities();...// 遍历userAuthorities,通过 GrantedAuthority 的 getAuthority 获取角色字符串,并添加到 set 集合中this.roles = AuthorityUtils.authorityListToSet(userAuthorities);
    }
    return this.roles;
    
  3. 遍历@hasRole中的角色(本文中只有 admin),如果当前登录信息的角色列表roleSet包含该角色,则通过校验。
    注意:校验时,会自动给 hasRole 中的角色添加默认前缀 ROLE_,所以在重写 getAuthorities 时需要添加上对应前缀

相关内容

热门资讯

DirectX12(D3D12... 目录1、前言1.1、一些感慨1.2、运行效果展示1.3、示例简介1.4、示例操作说明1.5、本章内容...
删除照片恢复,最实用的方法快收... 案例:删除照片恢复 “最近跟好朋友闹别扭了,一不小心把我们所有的合照都删...
1. 两数之和 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目...
香港《稳定币条例》正式成为法例 香港特别行政区政府于5月30日在宪报刊登《稳定币条例》,这意味着《稳定币条例》正式成为法例。 此前,...
Blender Apps?20... 2023 年对 Blender 来说将会是很有趣的一年,除了努力保持核心功能稳定和不断...
Leveraging Sali... Leveraging Saliency in Single-Stage Multi-Label Co...
Apache DophinSc... 前言 本文通过定时调度Python的例子演示了Apache DophinScheduler 的基本操...
牛客锦集 新手上路语法入门题解... 题单地址:选择结构题单 M 最大最小值 题意:输入三个数,...
《成都市体育发展条例》明起施行... 2025年,成都体育事业迎来关键节点,成都世运会开幕在即,一部重磅法规《成都市体育发展条例》正式出台...
springboot: 配置消... 问题描述 项目开发之前使用拦截器对controller的访问进行拦截,一切功能正常。今...