传统判断

传统对用户权限的判断通常通过调用权限Service的某个方法,比如:

1
2
3
4
5
6
7
// 获取用户权限
Role userRole = RoleService.getRole(user);
// 判断权限是否合格
if (userRole != Admin) {
throw new RuntimeException("权限不足")
}
// 执行逻辑....

这样的代码是不是重复性很高,在需要判断权限的每个地方都要这么写一遍,那么就可以抽出来成一个模板,还可以通过aop在方法外判断,保持方法内的逻辑清晰。

权限注解

通过权限注解指定方法需要的权限。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 用于权限校验当前用户
*
* @author <a href="https://github.com/Ershi-Gu">Ershi-Gu</a>
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthCheck {

/**
* 要求权限,默认要求超管权限
*
* @return {@link RoleEnum}
*/
RoleEnum requiredAuth() default RoleEnum.ADMIN;

}

权限判断

我们可以把放在方法中的权限判断抽取出来,那么就可以用的Spring AOP,增强方法而又不修改方法源码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 身份校验 AOP
*
* @author <a href="https://github.com/Ershi-Gu">Ershi-Gu</a>
*/
@Aspect
@Component
public class AuthCheckAspect {

@Resource
private UserRoleService userRoleService;

/**
* 执行拦截
*
* @param joinPoint
* @param authCheck
* @return
*/
@Around("@annotation(authCheck)")
public Object checkAuth(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
// 要求的权限
RoleEnum requiredAuth = authCheck.requiredAuth();
// 校验当前用户权限是否合格
Long uid = RequestHolder.get().getUid();
boolean authPass = userRoleService.checkAuth(uid, requiredAuth);
AssertUtil.isTrue(authPass, BusinessErrorEnum.NO_AUTH);
// 通过权限校验,放行
return joinPoint.proceed();
}
}

使用

只需要通过 @AuthCheck 指定好方法需要的权限,即可在aop中自行判断