Home > Back-end >  Access to XMLHttpRequest at 'http://localhost:8000/oauth/token' from origin react app has
Access to XMLHttpRequest at 'http://localhost:8000/oauth/token' from origin react app has

Time:10-08

I am using oauth2 in springboot for the server side and React application on the Client. I am sending the token request for the grant_type client_credentials to /oauth/token from react application and get the Above error.

I have used @CrossOrigin and also used http.cors() for the global security config but still keep seeing the Preflight cors block error in browser console.

Error:

Access to XMLHttpRequest at 'http://localhost:8000/oauth/token' 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. xhr.js:177 POST http://localhost:8000/oauth/token net::ERR_FAILED

CodePudding user response:

I think the main cause of the error is already highlighted in the error itself.

Response to preflight request doesn't pass access control check.

It means that spring security is in the picture for the preflight request and as pre-flight request doesn't contain any information about the authentication so spring security treat this request as coming from unauthenticated client and hence reject it.

You've to make ensure that CORS is handled first and you can achieve this by using the CorsFilter. You can use the CorsFilter with Spring Security by providing a CorsConfigurationSource using the following

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
        // You can restrict the origin and method in the following stmt according to the requirement
        configuration.setAllowedOrigins(Collections.singletonList(CorsConfiguration.ALL));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

CodePudding user response:

https://www.youtube.com/watch?v=7Yqb275FKmY helped me up. The issue was the @Order(Ordered.HIGHEST_PRECEDENCE) on my SimpleCORSFilter class that implements filter class.

  • Related