Cross Site forgery and Web API 2 RRS feed

  • Question

  • User955080112 posted

    I am attempting to prevent cross site forgery in Web API 2 using validate tokens and am experiencing a problem getting the code to execute.

    The code in the attribute class:

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public sealed class ValidateHeaderAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
        public void OnAuthorization(AuthorizationContext filterContext)
             if (filterContext == null)
                  throw new ArgumentNullException("filterContext");
             var httpContext = filterContext.HttpContext;
             var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
             AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);

    and in my post method, utilize the ValidateAntiForgeryToken attribute:

     [APIAuthorize(Roles = IdentityRoles.NsccAdministrator)]
     public int Post([FromBody] NsccNewPlanRequest data)
            // do some stuff and return 


    trouble is, I can't seem to get the process to execute the code in the ValidateHeaderAntiForgeryToken attribute. Everything is syntactically correct, and the attribute is recognized. It simply does not hit the OnAuthorization method breakpoint I set.

    Any ideas on why?

    Monday, October 5, 2020 6:40 PM


  • User475983607 posted

    It makes little sense to use an antiforgery token with Web API.  Typically, the token is is passed within an hidden form  field and a cookie.  Web API does not return HTML or cookies for that matter.

    Typically CORS is used to restrict/allow AJAX/fetch requests for the browser.  Securing Web API is typically done using bearer tokens (JWT) which identifies the user.  JWTs are signed and secured.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 5, 2020 7:06 PM