加入方法注解忽略权限验证,让你的代码更加优雅
1、忽略权限校验的方法注解IgnoreAuth,设定@Target使作用范围限定在方法上
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreAuth {
}
2、想不用权限验证的方法上,追加此注解
@IgnoreAuth
@GetMapping("list/{channelId}")
public ResponseResult list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
}
3、在拦截器中,判断方法是否使用了此注解,如果使用了,就不进行权限验证
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
IgnoreAuth annotation;
if (handler instanceof HandlerMethod) {
annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
} else {
return true;
}
// 如果有@IgnoreAuth注解,则不验证token
if (annotation != null) {
return true;
}
}
}
4、大功告成,自定义的注解,让代码显得更加优雅。