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.
Retrieval-Augmented Generation (RAG) is an innovative generative AI method that combines retrieval-based search with large…
The combination of Retrieval-Augmented Generation (RAG) and powerful language models enables the development of sophisticated…
Have you ever wondered how to use OpenAI APIs to create custom chatbots? With advancements…
When building a Retrieval-Augmented Generation (RAG) application powered by Large Language Models (LLMs), which combine…
Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…
Artificial Intelligence (AI) agents have started becoming an integral part of our lives. Imagine asking…