Skip to content

Instantly share code, notes, and snippets.

@nozzlegear
Last active March 15, 2024 00:11
Show Gist options
  • Save nozzlegear/eb3e4560580fc21f2032 to your computer and use it in GitHub Desktop.
Save nozzlegear/eb3e4560580fc21f2032 to your computer and use it in GitHub Desktop.
Validate an ASP.NET AntiForgeryToken sent in the request header
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
namespace MyNamespace.Controllers
{
[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"]);
}
}
}
@naunaucan
Copy link

where we can placed this code, on ActionFilters?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment