上级给了一个权限校验小程序的后端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相关的注解吗?
麻烦熟悉该相关的大佬替我解释一下,拜托了,感谢!