1. 程式人生 > 實用技巧 >自定義註解,實現指定介面token驗證,及踩坑

自定義註解,實現指定介面token驗證,及踩坑

最近專案,要實現部分指定介面驗證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)