Last active
March 17, 2016 08:51
-
-
Save blacktambourine/1d8fc12b37f5358a2cf1 to your computer and use it in GitHub Desktop.
Web API Antiforgery Attribute
This file contains hidden or 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
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