Skip to content

Instantly share code, notes, and snippets.

@osuritz
Created December 16, 2012 01:40
Show Gist options
  • Save osuritz/4302109 to your computer and use it in GitHub Desktop.
Save osuritz/4302109 to your computer and use it in GitHub Desktop.
.NET 4.5 / MVC4-compatible version of ValidateKsonAntiForgeryTokenAttribute
namespace Casero.Web.Mvc
{
using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
// Checks the User's CSRF token
// http://haacked.com/archive/2011/10/10/preventing-csrf-with-ajax.aspx
// Note: With MVC 4 the original technique couldn't be used so a modification has been made
// that uses the 2 overloads of AntiForgery.Validate()
/// <summary>
/// Represents an attribute that is used to detect whether a server request has been tampered with.
/// Improved over <see cref="ValidateAntiForgeryTokenAttribute"/> by checking for HTTP header (useful for JSON requests)
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
private const string AntiForgeryHeaderName = "X-CSRF-Token";
private const string AntiForgeryBuiltInFieldName = "__RequestVerificationToken";
private readonly HttpRequestBase _httpRequest;
public ValidateJsonAntiForgeryTokenAttribute(HttpRequestBase httpRequest)
{
this._httpRequest = httpRequest;
}
public ValidateJsonAntiForgeryTokenAttribute()
: this(new HttpRequestWrapper(HttpContext.Current.Request))
{
}
#region Implementation of IAuthorizationFilter
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
// Use header instead of form field when available
string antiForgeryHeader = this._httpRequest.Headers[AntiForgeryHeaderName];
if (antiForgeryHeader != null)
{
HttpCookie cookie = this._httpRequest.Cookies[AntiForgeryBuiltInFieldName];
if (cookie == null)
{
throw new HttpAntiForgeryException("Anti Forgery cookie was not found");
}
AntiForgery.Validate(cookie.Value, antiForgeryHeader);
}
else
{
AntiForgery.Validate();
}
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment