Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set CSRF Token to different context path

Our Angular based webapp is integrated with enterprise portal which runs on the different domain and context path. I am using Spring Security based CSRF token for validating the incoming requests. The app is perfectly working in local but when I integrate it with portal all the post calls are failing 403 because Angular is not able to read XSRF-Token and set the X-XSRF-Token in the request headers to the API calls. Upon investigation, I found the context paths of portal and our app are different and hence spring is setting the XSRF-Token with Path, Expires and domain as Null. Is there any way I can set XSRF-Token to a specific cookie path when spring creates it?

Note: I have an alternative solution to create filters and read the cookies from request headers and drop a new cookie on the browser with the path I want. I am looking for a solution at configuration level.

like image 216
javageek Avatar asked Feb 20 '17 21:02

javageek


People also ask

Where do I put CSRF token?

CSRF tokens are secrets and should be handled as such in a secure manner throughout their lifecycle. Place the field containing the CSRF token as early as possible within the HTML file. Place the field that contains the token before any non-hidden fields and before any places where user-controllable data is embedded.

How is CSRF token set?

A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client.

Is CSRF token always same?

Typically, this token is the same throughout the session, but in some circumstances it is more secure to rotate CSRF tokens often, or make them specific to the form they are on.

Can a CSRF token be used more than once?

The CSRF token sent in the state parameter is the "client side" of your usual CSRF token (the one you put in a hidden input field on your forms). Since the CSRF token will (by design) be sent in GET requests, it's advisable to make them unique and not reuse them.


1 Answers

In your configuration security (Java file), it's possible to add:

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

and to change in the function configure(...), the line:

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

with

http.csrf().csrfTokenRepository(this.getCsrfTokenRepository()).and()...

This permits to have a solution to personalize the path for the cookie XSRF-TOKEN.

like image 163
MaxL Avatar answered Nov 15 '22 02:11

MaxL