Created
August 2, 2012 00:39
-
-
Save kpol/3231954 to your computer and use it in GitHub Desktop.
ASP.NET MVC 2 -- ValidateAntiForgeryTokenAttribute for JSON requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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