如何基于SpringSecurity的@PreAuthorize实现自定义权限校验方法

一、前言

在我们一般的web系统中必不可少的就是权限的配置,也有经典的RBAC权限模型,是基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。当然SpringSecurity已经实现了权限的校验,但是不够灵活,我们可以自己写一下校验条件,从而更加的灵活!

很多开源框架中也是用的比较多,小编看了一下若依是自己写了一个注解实现的,pig是使用@PreAuthorize来实现自己的校验方式,小编以pig框架的为例。

二、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.  
  7. @Override
  8. public final boolean hasAnyAuthority(String authorities) {
  9.      return hasAnyAuthorityName(null, authorities);
  10. }
  11.  
  12. private boolean hasAnyAuthorityName(String prefix, String roles) {
  13.      Set<String> roleSet = getAuthoritySet();
  14.      // 便利规则,看看是否有权限
  15.      for (String role : roles) {
  16.          String defaultedRole = getRoleWithDefaultPrefix(prefix, role);
  17.          if (roleSet.contains(defaultedRole)) {
  18.              return true;
  19.          }
  20.      }
  21.      return false;
  22. }

三、权限校验判断工具

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

四、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表达式语法,

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

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

五、总结

这样就完成了自定义校验,具体的校验可以自己在配置里进行修改,当然也可以自己写一个注解来进行自定义校验,可以参考若依的注解!

到此这篇关于如何基于SpringSecurity的@PreAuthorize实现自定义权限校验方法的文章就介绍到这了,更多相关SpringSecurity自定义权限校验方法内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论