最近項目,要實現部分指定接口驗證token。於是就想到了,自定義注解來實現。看了一下,別人的實現自己也寫了一下。但是實際中也遇到了坑,后邊摸索半天終於解決了。
1.創建一個自定義注解,這里我只是作用在方法上,就沒有加作用在類上。
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface TokenVerification { }
2.創建一個攔截器,實現HandlerInterceptor。判斷接口上是否有注解,如果有則判斷請求是否攜帶token。未攜帶,則返回自定義封裝的response。若攜帶token,再
進行下一步操作。
@Component @Slf4j public class TokenVerificationInterceptor implements HandlerInterceptor { private static final String LOGIN_SESSION_KEY = "login_session"; @Autowired private StringRedisTemplate stringRedisTemplate; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { final HandlerMethod handlerMethod = (HandlerMethod) handler; final Method method = handlerMethod.getMethod(); TokenVerification tokenVerificationByMethod = AnnotationUtils.findAnnotation(method, TokenVerification.class); if (Objects.isNull(tokenVerificationByMethod)) return true; //判斷是否存在token String token = request.getHeader("token"); if (token == null) { returnValue(response); } else { String loginSession = stringRedisTemplate.opsForValue().get(token); if (null != loginSession) { request.setAttribute(LOGIN_SESSION_KEY, loginSession); } } } return true; } /** * token不存在設置返回值 * @param response * @throws IOException */ private void returnValue(HttpServletResponse response) throws IOException { ApiResult result = ApiResult.build(ResultCode.BAD_REQUEST + ResultCode.RESOURCE_COMMON + TalentpoolECode.TOKEN_NOT_EXIST, "token不存在"); ObjectMapper mapper = new ObjectMapper(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); response.getWriter().write(mapper.writeValueAsString(result)); } }
3.將攔截器注冊入,springmvc中。
@Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private TokenVerificationInterceptor tokenVerificationInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(tokenVerificationInterceptor).addPathPatterns("/**"); } }
4.使用方法,只需要在我們需要攔截的接口上 加入自定義注解。則可對此接口進行攔截token校驗。
@DeleteMapping("/{id}")
@TokenVerification
public ApiResult<Boolean> delete(@PathVariable Integer id) {
log.info("id update params: {}", JSON.toJSONString(id));
return clueCustomerWorkService.deleteClueWorkExperience(id);
}
這里注意在第二步,中 (handler instanceof HandlerMethod) 這個判斷,如果這里返回false則。會導致,錯誤的url被springMVC攔截處理。返回,則所有的錯誤url本來應該返回為404的url都會返回200.
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
(handler instanceof HandlerMethod)
