spring boot angular csrf token handshake error

Viewed 773

So I keep on getting a error regarding a request from my fronted (angular) to my backend (springboot). I have a assumption that I don't send it correctly from my frontend to the backend.

spring security config:

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable()
                .csrf()
                .csrfTokenRepository (this.getCsrfTokenRepository())
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:4200");

            }
        };
    }
    private CsrfTokenRepository getCsrfTokenRepository() {
        CookieCsrfTokenRepository tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse();
        tokenRepository.setCookiePath("/");
        return tokenRepository;
    }

angular requests:

 let url = "http://localhost:8080/api/v1/get_txt"
      this.http.get(url).subscribe(response => {
        console.log(response)

        // post request

        
      let _csrf = this.tokenExtractor.getToken() as string == null ? "test":this.tokenExtractor.getToken();
      const formData = new FormData();
      formData.append("name", "name")
      formData.append("_csrf", _csrf)
      let post = "http://localhost:8080/api/v1/testpost"

      this.http.post(post, formData, {
        headers: new HttpHeaders().set("X-XSRF-TOKEN", _csrf),//.set("Cookie", 'XSRF-TOKEN='+_csrf)
      })
        .subscribe(response => {
            console.log(response)
        })
      })

proof that the request gets sent: sent csrf token

What I also forget to mention is that I get a 403 error. I would be thankfull for every support, but I dont't want to disable the csrf token and not remove the spring boot dependency ;)

how I get the token:

app.module.ts:

    import:[HttpClientXsrfModule.withOptions({cookieName: 'XSRF-TOKEN'})]

app.component.ts
-> import
-> inject into constructor
let _csrf = this.tokenExtractor.getToken();

Update I found out that spring boot is failing to extract the cookie from the request. spring boot extract cookie error So it has to be the fault of the angular request...

1 Answers

A header name that you send from Angular is intended for using as HTTP parameter. In your code it would be let post = "http://localhost:8080/api/v1/testpost?_csrf=" + _csrf. So when CookieCsrfTokenRepository is set as CSRF token repository and you want to send it as header then default header name for this token is X-XSRF-TOKEN (as described here):

this.http.post(post, formData, {
        headers: new HttpHeaders().set("X-XSRF-TOKEN", _csrf)
})
...
Related