有的时候,我们要对接口进行管理,确定登录,然后就有了如下案例
继承
HandlerInterceptorAdapter抽象类进行接口鉴权
若接口不满意还可以选择如下接口
(HandlerInterceptorAdapter--->AsyncHandlerInterceptor--->HandlerInterceptor)
案例代码
启动类
import ;
import ;
@SpringBootApplication
public class Demo2Application {
public static void main(String[] args) {
(, args);
("OK.....");
}
}
配置类
import .;
import ;
import ;
import ;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//添加路径
(new AuthorizationInterceptor()).addPathPatterns("/test/**");
(new AuthorizationInterceptor()).addPathPatterns("/test2/**");
//排除路径
(new AuthorizationInterceptor()).excludePathPatterns("/api/login");
}
}
鉴权处理类(这里仅仅是判定UA长度进行判定,请自行替换)
import ;
import ;
import ;
import ;
import ;
import ;
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
} else {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = ();
String userAgent = ("User-Agent");
Boolean hasToken = false;
if (userAgent!=null&& ()>20){
hasToken=true;
}
("-------------------");
if ((() != null || ().getAnnotation() != null) && !hasToken) {
("鉴权失败");
return false;
} else {
("鉴权成功");
return true;
}
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
("结束");
}
}
注解
import ;
import ;
import ;
import ;
@Target({, })
@Retention()
public @interface Authorization {
}
控制层
import ;
import ;
import ;
@RestController
@RequestMapping("/test")
public class TestController1 {
@GetMapping(value = "/1")
public String getInfo() {
return "gatherLoginInfo";
}
@Authorization
@GetMapping(value = "/2")
public String getInfo2() {
return "gatherLoginInfo";
}
}