SpringBoot實現token校驗,能夠經過Filter或者HandlerInterceptor,兩種方式均可以,Filter在最外層,請求首先會經過Filter,filter容許請求才會經過Intercept。前端
下面以HandlerInterceptor實現爲例vue
1.實現HandlerInterceptor,攔截請求校驗tokensegmentfault
public class AuthenticationInterceptor implements HandlerInterceptor { private static final String URI_PASS_TOKEN = "/user/login"; @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception { log.info("authentication interceptor preHandle path:{} uri:{}",httpServletRequest.getServletPath(),httpServletRequest.getRequestURI()); // if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) { // return true; // } if (httpServletRequest.getRequestURI().endsWith(URI_PASS_TOKEN)) { return true; } //從http header裏面獲取token String token = httpServletRequest.getHeader("token"); if (StringUtils.isEmpty(token)) { throw new AuthenticationException(CODE_AUTHENTICATION_FAILED,"token is empty"); } Algorithm algorithm = Algorithm.HMAC256(JwtConstant.TOKEN_CREATE_SECRET); JWTVerifier verifier = JWT.require(algorithm).build(); try { verifier.verify(token); }catch (Exception ex){ throw new AuthenticationException(CODE_AUTHENTICATION_FAILED,ex.getMessage()); } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
2.Configuration配置,實現自動注入跨域
@Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authenticationInterceptor()) .addPathPatterns("/**"); } @Bean public AuthenticationInterceptor authenticationInterceptor() { return new AuthenticationInterceptor(); } }
經過單元測試、PostMan測試均可以調同,可是vue前端怎麼都沒法調用,錯誤以下:瀏覽器
參考https://segmentfault.com/a/11...
發現是瀏覽器發出的OPTIONS預檢請求被HandlerInterceptor攔截了,所以在HandlerInterceptor添加以下代碼:ide
if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) { return true; }
對於options的請求不進行token檢測便可post