2

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?

Batsheva
  • 85
  • 1

1 Answers1

2

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',
  }),
],
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • thanks for your answer. Is the 3td step is assuming the second step was not implemented as controller but as filter? can you provide filter example? and about the angular - after I import this modeule how do I use it? – Batsheva Dec 19 '19 at 09:01
  • No, you need the controller to get the cookie. The filter does the validation itself. – Athanasios Kataras Dec 19 '19 at 09:33