# Angular 2 – How to Secure Apps from CSRF/XSRF Attack

This blog represents concepts and code samples in relation with securing Angular apps from from CSRF or XSRF attack. The following points are covered:

• Different types of CSRF/XSRF tokens
• Server-side processing of XSRF tokens

### Different Types of CSRF/XSRF Tokens

CSRF/XSRF tokens can be of following different types:

• Per-session token: The token is generated once per session. With each request, the token is sent. Server verifies the correctness of the token and validity in terms of whether the token is expired or not.
• Per-request token: The token can be generated for each request and later verified and validated.

With Angular apps, any one of the above can be implemented as the token strategy such as above is implemented on server-side. Angular apps, in any case, sends the XSRF-TOKEN value as request header X-XSRF-TOKEN in each of the subsequent requests.

### Angular’s Default CookieXSRFStrategy for Processing Request-Response

Angular comes with built-in support for CSRF attack prevention in form of Angular HTTP service, by default, turning on CookieXSRFStrategy. CookieXSRFStrategy is an implementation of XSRFStrategy interface. As part of CookieXSRFStrategy, Angular does following with each request:

• Looks for a cookie, namely, XSRF-TOKEN in the server response that arrived.
• Sets X-XSRF-TOKEN as one of the request header. Set the value of X-XSRF-TOKEN header equal to the value of XSRF-TOKEN cookie returned earlier as part of the server response.

### Server-side Code to Process XSRF tokens

With X-XSRF-TOKEN set as request header, request is sent to the server. On server-side, the following is done:

• Server code looks for both, XSRF-TOKEN and X-XSRF-TOKEN and match their values. Server rejects the request if the values of XSRF-TOKEN and X-XSRF-TOKEN does not match.

Alternatively, different cookie names (in place of XSRF-TOKEN) can be used by the server. Accordingly, Angular can customize the cookie names appropriately by creating CookieXSRFStrategy with different cookie names. The following is the sample code:

{provide: XSRFStrategy, useValue: new CookieXSRFStrategy('custom-cookie', 'custom-headername')}


The custom CookieXSRFSTrategy , as mentioned previously, can be defined in the root module such as AppModule. The following code represents the same:

@NgModule({
imports: [ ... ],
declarations: [ ...],