This blog represents concepts and code samples in relation with securing Angular apps from from CSRF or XSRF attack. The following points are covered:
CSRF/XSRF tokens can be of following different types:
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 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:
With X-XSRF-TOKEN set as request header, request is sent to the server. On server-side, the following is done:
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: [ ...], providers: [ {provide: XSRFStrategy, useValue: new CookieXSRFStrategy('custom-cookie', 'custom-headername')},] bootstrap: [ AppComponent ] }) export class AppModule { }
The details such as above and much more can be obtained from my book, Building web apps with Spring 5 and Angular. Grab your ebook today and get started.
Last updated: 12th May, 2024 Data lakehouses are a relatively new concept in the data…
Last updated: 12th May 2024 In this blog, we get an overview of the machine…
Last updated: 12th May, 2024 In the world of generative AI models, autoencoders (AE) and…
Last updated: 7th May, 2024 Linear regression is a popular statistical method used to model…
Last updated: 3rd May, 2024 Have you ever wondered why some machine learning models perform…
Last updated: 2nd May, 2024 The success of machine learning models often depends on the…