I have a Spring Boot back-end application that runs on port 8888 and an Angular front-end app that runs on 4200.
In my Spring Boot application i've defined the following bean to handle CORS:
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
And my HttpSecurity
configuration looks like this:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
// ... the rest of the config
}
With this configuration everything works fine, i can successfully call my API from the Angular app.
But i would like to enable CSRF, so i've changed the security config to the following:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
// ... the rest of the config
}
And i've added the following HttpInterceptor
to my Angular app:
constructor(private tokenExtractor: HttpXsrfTokenExtractor) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.tokenExtractor.getToken();
if (token) {
req = req.clone({ setHeaders: { 'X-XSRF-TOKEN': token } });
}
return next.handle(req);
}
The problem is tokenExtractor.getToken()
always returns null
.
The corresponding request and response headers look like this:
The XSRF-TOKEN
response cookie is present.
I cannot figure out what the problem is.
I've tried importing the HttpClientXsrfModule
in my Angular app, but it doesn't make any difference.
I'd really appreciate any advice.