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.cs or Program.cs (depending on your project style):

 

Code
builder.Services.AddControllersWithViews()
    .AddRazorRuntimeCompilation();

builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "X-XSRF-TOKEN"; // Angular default
});

2. Send the CSRF Token to the Client

In your controller or middleware, expose the token via a cookie:

 

C#
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:

Code
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UpdateProfile(UserProfile profile)
{
    // Your logic here
}

 

 

 On the Angular Frontend

Angular has built-in support for CSRF via its HttpClientXsrfModule.

1. Enable CSRF Support

In app.module.ts:

Python
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-TOKEN cookie and adds it to the X-XSRF-TOKEN header for all outgoing requests.

 

2. Fetch the Token on App Init

Call the backend token endpoint when the app starts:

TypeScript
constructor(private http: HttpClient) {}

ngOnInit() {
  this.http.get('/api/antiforgery/token').subscribe();
}

 

 Best Practices

  • Use HTTPS to prevent token leakage.
  • Set SameSite=Strict or Lax on cookies to reduce CSRF risk.
  • Avoid storing tokens in localStorage—prefer cookies with HttpOnly=false for Angular to access them.
  • Combine with authentication (e.g., JWT or cookie-based auth) for full protection.