Spring Boot JWT CORS with Angular 6

后端 未结 5 949
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 22:24

I am using JWT in my Spring Boot app. When I try to login from the Angular 6 client, I get the CORS error

Access to XMLHttpRequest at \'http://localhost:8082         


        
5条回答
  •  温柔的废话
    2021-01-02 22:36

    Since message is about your preflight request i.e. OPTIONS request,

    I guess, you need to do two things on server side / Spring Boot code ,

    1. Return OK from Authentication filter so need to add below in attemptAuthentication method as first check i.e. don't do real authentication for preflight requests,

    if (CorsUtils.isPreFlightRequest(httpServletRequest)) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); return new Authentication() ; //whatever your token implementation class is - return an instance of it
    }

    CorsUtils is - org.springframework.web.cors.CorsUtils

    1. Let Spring Security Enter Authorized Options requests into System so add these lines in Security Config ,

    .authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

    You can allow unauthorized OPTIONS requests too but I guess , that wouldn't be a good idea. Also, try to narrow down "/**" to specific URLs if possible.

提交回复
热议问题