Ad

CORS Issue - Response To Preflight Request Doesn't Pass Access Control Check:

- 1 answer

I am working on reactjs frontend with is using a spring boot in backend. I am trying to calling the end point from frontend as follows :

testOktaTokenAtRest(data) {
  var oauth=JSON.parse(localStorage.getItem('okta-token-storage'))
  console.log("toekn is: ==>  "+oauth.accessToken.tokenType + 
  oauth.accessToken.accessToken)
  console.log("toekn received from action is inside this obj: ",data)
  var searchCriteria = JSON.stringify(data.data)
  console.log("searchCriteria data -------: " , searchCriteria)

 let _headerForSearch={
    auth : 'Bearer ' + oauth.accessToken.accessToken 
  }
  $.ajax({
    method: "post",
    url: "http://localhost:8000/ckcapp/api/posttest",
    contentType: "application/json",
    dataType: "json",
    data:searchCriteria,
    beforeSend: function (xhr) {
      xhr.setRequestHeader("Authorization", _headerForSearch.auth);
    },
    success: function(response) {

      console.log("response from okta enabled get api is: ",response)
    },
    error: function(xhr, status, error) {
      console.log("error from okta enabled get api is: ",xhr.responseText 
     + " " +status + " " + error );
    }
  });


  }

When i make request, i get the following error :-

Access to XMLHttpRequest at 'http://localhost:8000/ckcapp/api/posttest' from origin 'http://localhost:3000' has been blocked by CORS policy: response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My spring-boot application has following configuration:

CORSFilter
    public class CORSFilter implements Filter {


    private static final String ONE_HOUR = "3600";

      @Override
      public void init(FilterConfig filterConfig) throws ServletException 
    {
      }

      @Override
      public void doFilter(ServletRequest req, ServletResponse res, 
    FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", 
    "http://localhost:3000");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, 
    GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", ONE_HOUR);
        response.setHeader("Access-Control-Request-Headers", 
    "authorization,content-type");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested- 
    With,Origin,Content-Type, Accept, x-device-user-agent, Content-Type");

        if (req instanceof HttpServletRequest) {
           HttpServletRequest httpServletRequest = (HttpServletRequest) 
    req;
           if (httpServletRequest.getHeader(HttpHeaders.ORIGIN) != null
              && 
      httpServletRequest.getMethod().equals(HttpMethod.OPTIONS.name())
              && 
    httpServletRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD) 
    != 
    null) {

              return;
           }
        }
        chain.doFilter(req, res);
      }

      @Override
      public void destroy() {
      } 
    }

and my i am calling the endpoint as :

 @RestController
    @CrossOrigin(origins = "http://localhost:3000")
    public class CkcOktaController {
        @PostMapping("/api/posttest")
    @PreAuthorize("hasAuthority('SCOPE_email')")
    public String setString(@RequestBody CustomerDetailsNew 
        customerDetails) {
        System.out.println("In post method ");
        System.out.println("text :" + customerDetails.toString());
        System.out.println("text :" + customerDetails.getEntityId());
        return "Success";
    }
    }

I think I am missing some configuration.

The application is protected by OKTA.

Ad

Answer

I am using React with Spring JWT faced similar issue as blocked by CORS policy .

added http.cors() in my SecurityConfigurer class to resolve

@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().......
    }
}

controller

@CrossOrigin(origins = {"http://localhost:3000"})
@RestController
Ad
source: stackoverflow.com
Ad