Search code examples
reactjsspringspring-securityaxioscsrf

React, SpringBoot and CSRF


I am using Spring Boot Security:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

I have disabled CSRF:

@Slf4j
@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {

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

    }
}

Using npm start, I run the following code in my React app:

         axios
            .post(this.state.targetUrl+'/mpbpm/triggerProcess', {
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS'
                }
            })

The result is:

Failed to load http://localhost:8080/mpbpm/triggerProcess: Response for preflight has invalid HTTP status code 401.

Why has this failed? I am trying to learn React, I have dummy code trying to retrieve values from a server. What is the easiest way to get this working?


Solution

  • here:

             axios
                .post(this.state.targetUrl+'/mpbpm/triggerProcess', {
                    headers: {
                        'Access-Control-Allow-Origin': '*',
                        'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS'
                    }
                })
    

    you're adding custom headers and send cross-origin fetch which triggers preflight request. The server isn't prepared for this kind of traffic and everything results in an error. Remove those headers.