Skip to content

Instantly share code, notes, and snippets.

@blacktambourine
Last active March 17, 2016 08:51
Show Gist options
  • Save blacktambourine/1d8fc12b37f5358a2cf1 to your computer and use it in GitHub Desktop.
Save blacktambourine/1d8fc12b37f5358a2cf1 to your computer and use it in GitHub Desktop.
Web API Antiforgery Attribute
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace Example.WebAPI.Attributes
{
/// <summary>
/// Anti-forgery token check that works with Angular JS and Web API
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class CustomAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
try
{
//Cookie value - had to parse cookie value this way as GetCookies() returns null in certain circumstances
var cookieList = actionContext.Request.Headers.ToList().FirstOrDefault(x => x.Key == "Cookie").Value.FirstOrDefault();
if (cookieList == null)
{
throw new Exception("Cookies are missing");
}
var cookieElements = cookieList.Split(';');
var cookie = cookieElements.FirstOrDefault(x => x.Trim().StartsWith(AntiForgeryConfig.CookieName));
if (cookie == null)
{
throw new Exception("Cookies do not contain Anti-forgery token.");
}
var cookieValue = cookie.Replace(AntiForgeryConfig.CookieName + "=", string.Empty);
if (string.IsNullOrEmpty(cookieValue))
{
throw new Exception("Cookies do not contain Anti-forgery token.");
}
//Form value
var clientToken = actionContext.Request.Headers.FirstOrDefault(x => x.Key == "X-XSRF-Token").Value.FirstOrDefault();
if (clientToken == null)
{
throw new Exception("Header does not contain Anti-forgery token.");
}
AntiForgery.Validate(cookieValue, clientToken);
}
catch
{
actionContext.Response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.Forbidden,
RequestMessage = actionContext.ControllerContext.Request
};
return AttributeHelpers.FromResult(actionContext.Response);
}
return continuation();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment