SpringBoot JWT Token 跨域 Preflight response is not successful

1、Springboot實現token校驗

SpringBoot實現token校驗,能夠經過Filter或者HandlerInterceptor,兩種方式均可以,Filter在最外層,請求首先會經過Filter,filter容許請求才會經過Intercept。
1080989-20171111220901372-1350981631.png前端

下面以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();
    }
}

2、前端調用 跨域 Preflight response is not successful

經過單元測試、PostMan測試均可以調同,可是vue前端怎麼都沒法調用,錯誤以下:瀏覽器

clipboard.png

clipboard.png

參考https://segmentfault.com/a/11...
發現是瀏覽器發出的OPTIONS預檢請求被HandlerInterceptor攔截了,所以在HandlerInterceptor添加以下代碼:ide

if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
            return true;
        }

對於options的請求不進行token檢測便可post

相關文章
相關標籤/搜索