Skip to content

Instantly share code, notes, and snippets.

@kpol
Created August 2, 2012 00:39
Show Gist options
  • Save kpol/3231954 to your computer and use it in GitHub Desktop.
Save kpol/3231954 to your computer and use it in GitHub Desktop.
ASP.NET MVC 2 -- ValidateAntiForgeryTokenAttribute for JSON requests
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
var httpContext = new JsonAntiForgeryHttpContextWrapper(HttpContext.Current);
filterContext.HttpContext = httpContext;
new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
}
public string Salt
{
get;
set;
}
private class JsonAntiForgeryHttpContextWrapper : HttpContextWrapper
{
private readonly HttpRequestBase _request;
public JsonAntiForgeryHttpContextWrapper(HttpContext httpContext)
: base(httpContext)
{
_request = new JsonAntiForgeryHttpRequestWrapper(httpContext.Request);
}
public override HttpRequestBase Request
{
get
{
return _request;
}
}
}
private class JsonAntiForgeryHttpRequestWrapper : HttpRequestWrapper
{
private readonly NameValueCollection _form;
public JsonAntiForgeryHttpRequestWrapper(HttpRequest request)
: base(request)
{
_form = new NameValueCollection(request.Form);
if (request.Headers["__RequestVerificationToken"] != null)
{
_form["__RequestVerificationToken"] = request.Headers["__RequestVerificationToken"];
}
}
public override NameValueCollection Form
{
get
{
return _form;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment