Search code examples
reactjsspring-bootthymeleafcsrf

React + springboot csrf


i've a react application inside a springboot project, the react application use rest calls for get/set stuff. Actually i've disabled csrf inside the configure adapter .csrf().disable() but i'd like to menage this. How can i handle csrf token between react and springboot?

I think that i should pass the token through my axios call, but how i get it?

Thanks


Solution

  • You need to save CSRF-TOKEN to cookie and send it back with the request header.

    SecurityConfig class.

    Enable csrftokenrepsitory

             .csrf().csrfTokenRepository(csrfTokenRepository()).and().addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class).addFilterAfter(new XSSFilter(), CsrfFilter.class);
    

    Add csrfTokenRepository

           private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName(X_CSRF_TOKEN);
        return repository;
    }
    

    In react, you can access token from the cookie.

        csrfToken=  cookies.get('XSRF-TOKEN');
    

    Send it as follows in the header.

         headers: {
        'X-XSRF-TOKEN': this.csrfToken,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
    

    https://github.com/supun/okta-spring-boot-react-crud-example/blob/master/src/main/java/com/okta/developer/jugtours/config/SecurityConfiguration.java