Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringBoot - Angular 5 - CSRF

Iam lost now and need some help.

I have a

  • SpringBoot Server with SpringSecurtiy 4.3.
  • Angular 5 App

And want to enable CSRF protection since it should be enabled on both by default (says the docs) :Its NOT!

On SpringBoot I need to add these security configs:

http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

On Angular I need to add these Modules:

imports: [
    ...,
    HttpClientModule,
    HttpClientXsrfModule, //(!)
...

Bottom line the server send the XRSF-TOKEN in each response.

-But a diffrent on each one. Is that correct? I expected to be the same on a client session.

-Main problem here is that Angular5 still didnt use the XRSF-TOKEN in its post calls (e.g.). It dont set a X-XSRF-TOKEN in its requests.

What am I doing wrong or missing?

like image 517
Gregor Sklorz Avatar asked Nov 16 '17 16:11

Gregor Sklorz


People also ask

How does spring boot handle CSRF?

To protect MVC applications, Spring adds a CSRF token to each generated view. This token must be submitted to the server on every HTTP request that modifies state (PATCH, POST, PUT and DELETE — not GET). This protects our application against CSRF attacks since an attacker can't get this token from their own page.

Does angular have CSRF protection?

CSRF support in Angular Angular has built-in support for a flavor of the Double Submit Cookie Pattern, where the CSRF token is automatically added as an HTTP header for every backend request once you have a CSRF token in a cookie. Nice! The HttpClientXsrfModule automatically adds an interceptor for your HTTP requests.

Where is CSRF token in spring boot?

The server will create a CSRF token (token1) and store that token in the HttpSession. The CSRF token (token1) is also be embedded in the form on the client side. The client is also given a Session ID (session-id1) which is stored in a cookie.

Is CSRF needed for REST API?

The CSRF token is required for any later REST API calls. The client must send a valid token with every API request. The token is sent in a custom request HTTP header.


1 Answers

I had this same problem and I think it is a regression due to version 5 of angular.

Until this is fixed you can add your own 'X-XSRF-TOKEN' header as I did.

 constructor(private http: HttpClient, private tokenExtractor: HttpXsrfTokenExtractor) {
    }

then extract manually a token

const token = this.tokenExtractor.getToken() as string;

and add it to the header

this.http.post<any>(url, body, {headers: new HttpHeaders().set('X-XSRF-TOKEN', token)})

Houssem

like image 73
H.abidi Avatar answered Sep 28 '22 17:09

H.abidi