Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Deepika SawantRank #242 · 10.2K reputationPosted Oct 13, 2025, 9:26 AM EDT
To implement CSRF protection in Angular and .NET (ASP.NET Core), use the anti-forgery token mechanism on the server and configure Angular to send the token with each request. This ensures that only trusted clients can perform authenticated actions.
On the .NET (ASP.NET Core) Backend
ASP.NET Core provides built-in CSRF protection via the Antiforgery middleware.
1. Enable Antiforgery Services
In
Startup.csorProgram.cs(depending on your project style):2. Send the CSRF Token to the Client
In your controller or middleware, expose the token via a cookie:
public class AntiforgeryController : Controller { private readonly IAntiforgery _antiforgery; public AntiforgeryController(IAntiforgery antiforgery) { _antiforgery = antiforgery; } [HttpGet("/api/antiforgery/token")] public IActionResult GetToken() { var tokens = _antiforgery.GetAndStoreTokens(HttpContext); Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken!, new CookieOptions { HttpOnly = false }); return Ok(); } }Call this endpoint from Angular on app load or login.
3. Validate the Token
Use
[ValidateAntiForgeryToken]on your POST/PUT/DELETE actions:On the Angular Frontend
Angular has built-in support for CSRF via its
HttpClientXsrfModule.1. Enable CSRF Support
In
app.module.ts:import { HttpClientXsrfModule } from '@angular/common/http'; @NgModule({ imports: [ HttpClientXsrfModule.withOptions({ cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN' }) ] }) export class AppModule {}This automatically reads the
XSRF-TOKENcookie and adds it to theX-XSRF-TOKENheader for all outgoing requests.2. Fetch the Token on App Init
Call the backend token endpoint when the app starts:
constructor(private http: HttpClient) {} ngOnInit() { this.http.get('/api/antiforgery/token').subscribe(); }Best Practices
SameSite=StrictorLaxon cookies to reduce CSRF risk.HttpOnly=falsefor Angular to access them.