Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement ValidateAntiForgeryToken with angular 7 and asp.net web api

My app's server side is built in Asp.Net web api and the client side is angular 7.

I can find many examples of how to implement ValidateAntiForgeryToken when using web forms, angularjs, working with Razor and etc.

But I cannot find any article or quesion explaining how to implement this with web api and how to call it from the angular service.

Can someone show a short example of the server side and client side implementing this?

like image 343
Batsheva Avatar asked Feb 21 '26 10:02

Batsheva


1 Answers

You can use a combination of the following:

Web api create antiforgery token guide

  1. Setup the application
    public void ConfigureServices(IServiceCollection services)
    {      
        services.AddAntiforgery(options =>
        {
            options.HeaderName = "X-XSRF-TOKEN";                               
        });
  1. Create the controller action that will get you the token. You can also do this in a filter.
[ApiController]
public class AntiForgeryController : Controller
{
    private IAntiforgery _antiForgery;
    public AntiForgeryController(IAntiforgery antiForgery)
    {
        _antiForgery = antiForgery;
    }

  [Route("api/antiforgery")]
  [IgnoreAntiforgeryToken]
  public IActionResult GenerateAntiForgeryTokens()
  {
      var tokens = _antiForgery.GetAndStoreTokens(HttpContext);
      Response.Cookies.Append("XSRF-REQUEST-TOKEN", tokens.RequestToken, new Microsoft.AspNetCore.Http.CookieOptions
      {
          HttpOnly = false
      });            
      return NoContent();
  }
  1. Apply it to every controller
public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddMvc(options =>
    {
        options.Filters.Add(new ValidateAntiForgeryTokenAttribute());
    });
    //...

Now for the client side, you can use the built in antiforgery mechanism http angular guide

imports: [
  HttpClientModule,
  HttpClientXsrfModule.withOptions({
    cookieName: 'Enter chosen name',
    headerName: 'Enter chosen name',
  }),
],
like image 157
Athanasios Kataras Avatar answered Feb 23 '26 03:02

Athanasios Kataras