传统判断
传统对用户权限的判断通常通过调用权限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
|
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AuthCheck {
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
|
@Aspect @Component public class AuthCheckAspect {
@Resource private UserRoleService userRoleService;
@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中自行判断
