Pete
Pete

Reputation: 61

How do you include a CSRF token in a Vue.js application with a Spring Boot backend?

I'm trying to do a POST request to my backend REST API using the browser's Fetch API like this:

   submitRegistration() {
         const formElement = document.getElementById('register-form');
         fetch('http://localhost:8080/register', {
             method: 'POST',
             body: new FormData(formElement),
         });
     }

I'm taking the data from this form:

<v-form id="register-form" @submit.prevent="submitRegistration" class="text-center" ref="form" v-model="valid" lazy-validation>
    <v-text-field type="text" name="username" v-model="form.username" :counter="25" :rules="usernameRules" label="Username" required></v-text-field>
    <v-text-field type="password" name="userPassword" v-model="form.password" :counter="25" :rules="passwordRules" label="Password" required></v-text-field>
    <v-text-field type="text" name="userEmail" v-model="form.email" :rules="emailRules" label="E-mail" required></v-text-field>
    <v-btn type="submit" text class="primary">Register</v-btn>
</v-form>

However, as a response I get 403 Forbidden by my backend server. The problem is the CSRF token but I have no idea how to generate it to include it in the POST request to the backend API.

EDIT: In Spring Boot, my CORS mapping is configured like this:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:9000").allowCredentials(true);
        }
    };
}

I'm posting this because the Response object that is returned gives me a 403 status and is of type "cors" even though the error is resolved if I completely disable CSRF using HttpSecurity - http.csrf().disable();

Upvotes: 2

Views: 8960

Answers (1)

Pete
Pete

Reputation: 61

This could be solved by making a GET call first to the server and then following the solution here with the following additions / corrections:

  1. In the submitRegistration() method, add the following at the top:

        // Do a fetch to GET the XSRF-TOKEN as a cookie
        fetch('http://localhost:8080/register');
        const csrfToken = this.getCookie('XSRF-TOKEN');
        const headers = new Headers({
            'X-XSRF-TOKEN': csrfToken
        });
    
  2. Our POST request now looks like this:

       fetch('http://localhost:8080/register', {
            method: 'POST',
            headers,
            credentials: 'include',
            body: new FormData(formElement),
        })
    
  3. In the backend, we need to add the following to our overriden configure() method:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
    

    This tells the server to send back the CSRF token as a cookie called "XSRF-TOKEN" and reads the CSRF token from a header called "X-XSRF-TOKEN".

Upvotes: 2

Related Questions