哪里可以做網(wǎng)站推廣win7優(yōu)化大師好不好
本篇文章的主要內(nèi)容是通過AOP切面編程實現(xiàn)簡單的權(quán)限校驗。
書接上回登錄與注冊功能
我們的用戶表里面不是有role(權(quán)限)這個字段嗎
在JWT令牌的生成中,我們加入了role字段。
那么接下來,我們就可以通過這個字段來實現(xiàn)權(quán)限校驗。
我這里就很簡單,只有一個Permission注解和一個PermissionAspect類
Permission
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface Permission {/*** 最小權(quán)限* @return*/int role() default 0;
}
PermissionAspect類:
@Slf4j
@Aspect
@Component
public class PermissionAspect {// 定義切點@Pointcut("within(@org.springframework.web.bind.annotation.RestController *) && @annotation(com.codehome.server.annotation.Permission)")public void autoPermissionPointcut(){}// 定義通知@Before("autoPermissionPointcut()")public void requirePermission(final JoinPoint joinPoint)throws PermissionException {log.info("權(quán)限校驗開始");MethodSignature signature = (MethodSignature) joinPoint.getSignature();Permission permission = signature.getMethod().getAnnotation(Permission.class);Integer role = permission.role();if(BaseContext.getCurrentRole() >= role){log.info("權(quán)限校驗通過");}else {throw new PermissionException("權(quán)限不足");}}
}
說明:在JWT令牌生成的時候我們存入了role,在JwtTokenAdminInterceptor攔截器中,我們將這個role取了出來并保存到了ThreadLocal中,所以在校驗的時候,就通過這個role進(jìn)行權(quán)限校驗。
權(quán)限校驗使用:
在Controller類中,我們在每個路徑方法前加上我們寫的注解@Permission(role=2)
,這個就代表著只有用戶權(quán)限大于等于2的用戶發(fā)送到這個路徑的請求才能被放行處理。這樣就特別靈活。