Ivaldir
Ivaldir

Reputation: 195

Axios request gets stopped by CORS

I have a react based frontend and a spring backend (which uses spring security). I have disabled CORS in the spring security configuration (at least I think so) but the requests still gives this error:

Access to XMLHttpRequest at 'http://localhost:8080/api/v1/registration/' 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.

This is the frontend:

const register = () => {
        //var url = process.env.REACT_APP_SERVER_IP + "/api/v1/registration";
        var url = "http://localhost:8080/api/v1/registration/";
        var userData = {
            email: "[email protected]",
            username: "uname",
            password: "pass"
        }

        axios.post("http://localhost:8080/api/v1/registration/", userData
        ).then(function (response) {
            alert(response);
        }).catch(function (error) {
            alert(error);
        });
    }

This is the backend:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/v*/registration/**")
                .permitAll()

                .anyRequest()
                .authenticated().and()
                .formLogin();
    }

Any idea as to why requests are still blocked?

Upvotes: 1

Views: 1375

Answers (3)

Ivaldir
Ivaldir

Reputation: 195

I solved the problem by adding in the react application as an exception. The security settings are as follows:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors();
    http.csrf().disable();

    // Authorize all requests.
    http.authorizeRequests()
        .antMatchers("/api/v*/registration/**")
        .permitAll()
        .anyRequest()
        .authenticated().and()
        .formLogin();
}

The react application was set as an exeption using this bean within the security config.

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList(corsConfig.getAddress()));
    configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    configuration.setExposedHeaders(Arrays.asList("Authorization", "content-type"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

Here the corsConfig.getAddress() gets the address of the react application from a config I setup, for example http://localhost:3000. Also note that in the code csrf is disabled, which as others have noted isn't a great idea.

Upvotes: 2

Toerktumlare
Toerktumlare

Reputation: 14787

you have not disabled cors. You have missed stating disable after the cors declaration.

http.cors().disable()
    .and()
    .csrf().disable()

Remember it's bad practice to disable cors and csrf they are security features there to protect your application.

Upvotes: 0

verodigiorgio
verodigiorgio

Reputation: 363

I think this question is duplicated

The CORS blocks requests on the client and is your browser that is preventing the ajax requests to be executed because the server is not allowing them.

The server can actually choose to return something that the client allows or not.

In this case you probably should enabled the CORS support in Spring so that OPTIONS requests are allowed even if not in a secure request.

You should then configure the CORS allowed origins, methods and other relative configuration accordingly.

Find more on Cross-Origin Resource Sharing (CORS) here

Upvotes: -1

Related Questions