3

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?

1

1 Answer 1

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',
  }),
],
Sign up to request clarification or add additional context in comments.

2 Comments

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?
No, you need the controller to get the cookie. The filter does the validation itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.