一、前言

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

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

二、SpringSecurity的@PreAuthorize

@PreAuthorize("hasAuthority('system:dept:list')")@GetMapping("/hello")public String hello (){    return "hello";}

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

// 调用的方法@Overridepublic final boolean hasAuthority(String authority) {return hasAnyAuthority(authority);}@Overridepublic final boolean hasAnyAuthority(String... authorities) {return hasAnyAuthorityName(null, authorities);}private boolean hasAnyAuthorityName(String prefix, String... roles) {Set roleSet = getAuthoritySet();// 便利规则,看看是否有权限for (String role : roles) {String defaultedRole = getRoleWithDefaultPrefix(prefix, role);if (roleSet.contains(defaultedRole)) {return true;}}return false;}

三、权限校验判断工具

@Component("pms")public class PermissionService {/** * 判断接口是否有xxx:xxx权限 * @param permission 权限 * @return {boolean} */public boolean hasPermission(String permission) {if (StrUtil.isBlank(permission)) {return false;}Authentication authentication = SecurityContextHolder.getContext().getAuthentication();if (authentication == null) {return false;}Collection authorities = authentication.getAuthorities();return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText).anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));}}

四、controller使用

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

参数说明:

主要是采用SpEL表达式语法,
@pms:是一个我们自己配置的spring容器起的别名,能够正确的找到这个容器类;
hasPermission('order_get'):容器内方法名称和参数

五、总结

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


有缘人才可以看得到的哦!!!

点击访问!小编自己的网站,里面也是有很多好的文章哦!