基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验

其他教程   发布日期:2024年10月30日   浏览次数:342

这篇文章主要介绍“基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验”,在日常操作中,相信很多人在基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

一、前言

在我们一般的web系统中必不可少的就是权限的配置,也有经典的RBAC权限模型,是基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。当然

  1. SpringSecurity
已经实现了权限的校验,但是不够灵活,我们可以自己写一下校验条件,从而更加的灵活!

二、SpringSecurity的@PreAuthorize

  1. @PreAuthorize("hasAuthority('system:dept:list')")
  2. @GetMapping("/hello")
  3. public String hello (){
  4. return "hello";
  5. }

我们进去源码方法中看看具体实现,我们进行模仿!

  1. // 调用的方法
  2. @Override
  3. public final boolean hasAuthority(String authority) {
  4. return hasAnyAuthority(authority);
  5. }
  6. @Override
  7. public final boolean hasAnyAuthority(String... authorities) {
  8. return hasAnyAuthorityName(null, authorities);
  9. }
  10. private boolean hasAnyAuthorityName(String prefix, String... roles) {
  11. Set<String> roleSet = getAuthoritySet();
  12. // 便利规则,看看是否有权限
  13. for (String role : roles) {
  14. String defaultedRole = getRoleWithDefaultPrefix(prefix, role);
  15. if (roleSet.contains(defaultedRole)) {
  16. return true;
  17. }
  18. }
  19. return false;
  20. }

三、权限校验判断工具

  1. @Component("pms")
  2. public class PermissionService {
  3. /**
  4. * 判断接口是否有xxx:xxx权限
  5. * @param permission 权限
  6. * @return {boolean}
  7. */
  8. public boolean hasPermission(String permission) {
  9. if (StrUtil.isBlank(permission)) {
  10. return false;
  11. }
  12. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  13. if (authentication == null) {
  14. return false;
  15. }
  16. Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
  17. return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText)
  18. .anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
  19. }
  20. }

四、controller使用

  1. @GetMapping("/page" )
  2. @PreAuthorize("@pms.hasPermission('order_get')" )
  3. public R getOrderInPage(Page page, OrderInRequest request) {
  4. return R.ok(orderInService.queryPage(page, request));
  5. }

参数说明:

主要是采用SpEL表达式语法,

  1. @pms
:是一个我们自己配置的spring容器起的别名,能够正确的找到这个容器类;

  1. hasPermission('order_get')
:容器内方法名称和参数

以上就是基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验的详细内容,更多关于基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验的资料请关注九品源码其它相关文章!