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.
In this blog, I aim to provide a comprehensive list of valuable resources for learning…
Have you ever wondered how systems determine whether to grant or deny access, and how…
What revolutionary technologies and industries will define the future of business in 2025? As we…
For data scientists and machine learning researchers, 2024 has been a landmark year in AI…
ChatGPT Canvas is a cutting-edge, user-friendly platform that simplifies content creation and elevates collaboration. Whether…
Knowing when to use the LLM such as the ChatGPT O1 model is key to…