柰茶 2020-04-06 16:43 采纳率: 0%
浏览 721
已采纳

如何理解这个自定义注解实现权限校验

上级给了一个权限校验小程序的后端demo,是通过自定义注解、jwt来实现校验token的。但是我就是没看明白这个拦截器的部分,请问一下Authorize是加到哪里的注解?是加到小程序发起的请求里吗?
自定义注解Authorize:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorize {
    boolean required() default true;
}

拦截器部分:

public class AuthorizationInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
    // 如果不是映射到方法直接通过
    if (!(object instanceof HandlerMethod)) {
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) object;
    Method method = handlerMethod.getMethod();

    //检查有没有需要用户权限的注解
    //如果有注解Authorize,就需要验证token
   ** if (method.isAnnotationPresent(Authorize.class)) {**
        Authorize userLoginToken = method.getAnnotation(Authorize.class);
        if (userLoginToken.required()) {

            String token = httpServletRequest.getHeader("authorization");// 从 http 请求头中取出 token

            // 执行认证
            if (token == null) {
                throw new RuntimeException("无token,请重新登录");
            }
                            .......

什么情况下会进入if (method.isAnnotationPresent(Authorize.class)) {里面?怎么使得

   HandlerMethod handlerMethod = (HandlerMethod) object;
    Method method = handlerMethod.getMethod();

这个method里面有Authorize注解?难道可以在小程序端发起的请求URL或Meothod里加Authorize相关的注解吗?

麻烦熟悉该相关的大佬替我解释一下,拜托了,感谢!

  • 写回答

1条回答 默认 最新

  • VICTOR_fusheng 2020-04-07 09:45
    关注

    method.isAnnotationPresent(Authorize.class)这个判断方法上是否有Authorize注解,有这个注解的才校验token,你可以看controller里的方法。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗