Search code examples
spring-bootreact-reduxaxiosspring-oauth2

Cannot send POST request to Spring Resource server


I have a Spring Boot ResourceServer, and a React client application. I am trying to send a POST request to one of the server endpoints (which has the @CrossOrigin annotation btw.), however, I am getting this error in the console:

Access to XMLHttpRequest at 'http://localhost:8080/api/search' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

The preflight request returns a 401 Http status, and I don't know why.

The response headers for the preflight request look like this:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: http://localhost:3000
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Sun, 20 Oct 2019 17:23:54 GMT
Expires: 0
Pragma: no-cache
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
WWW-Authenticate: Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

My preflight request headers look like this:

Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://localhost:3000
Referer: http://localhost:3000/movie-search
Sec-Fetch-Mode: no-cors
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36

I am using Axios to send the request (if that matters). Anyone knows what's going on here?


Solution

  • Whoops...my HTTPSecurity config looked like this:

    http
        .authorizeRequests()
        .antMatchers(HTTPMethod.POST, "/api/search").permitAll()
        .anyRequest().authenticated()
        .and().httpBasic()
    

    instead of this:

    http
        .authorizeRequests()
        .antMatchers("/api/search").permitAll()
        .anyRequest().authenticated()
        .and().httpBasic()