Search code examples
angularasp.net-web-apiasp.net-core-webapiantiforgerytoken

Anti forgery with token API and angular


I am working on Angular 6 application with SSO login and .net core web API. The code hits the back end on /token url first time which is a post operation. How do I do the anti forgery in this scenario. Please explain the flow of token transfer


Solution

  • This question is old however my solution could help somebody. What worked for us:

    • on Angular FE side HttpXsrfTokenInterceptor is used which is setting X-XSRF-TOKEN header. Of course cookie has to contain token under XSRF-TOKEN

    • on .net core side: Basically approach describe above, using domstamand's approach. However, and this is important, you have to add validation action into the middleware. Apparently using your custom middlaware turn's off validation done OOB by .net core antiforgery service. So after update your code for Invoke method should looks like this:

       public Task Invoke(HttpContext context)
       {
           if (context.Request.Headers.ContainsKey("X-XSRF-TOKEN"))
           {
               _antiForgery.ValidateRequestAsync(context);
           }
      
           var tokens = _antiForgery.GetAndStoreTokens(context);
           context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { 
               HttpOnly = false,
               Secure = true
           });
      
           return _next(context);
       }
      

    I added check for X-XSRF-TOKEN to avoid possible issues e.g. when GET or OPTIONS preflight check is called.

    Update: Problem with my solution is that if you don't include X-XSRF-TOKEN into the HTTP request header validation doesn't execute at all. I trying to find fix for that.