Skip to content

Instantly share code, notes, and snippets.

@3nth
Created September 21, 2014 19:45
Show Gist options
  • Save 3nth/6cc30c3b16e64073656f to your computer and use it in GitHub Desktop.
Save 3nth/6cc30c3b16e64073656f to your computer and use it in GitHub Desktop.
Add AntiForgeryToken to Response Header
public class AddCsrfTokenHeader:ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
HttpCookie cookie = null;
// First, try and get cookie from Response. That'll be a new cookie
if (filterContext.HttpContext.Response.Cookies.AllKeys.Contains(AntiForgeryConfig.CookieName))
{
cookie = filterContext.HttpContext.Response.Cookies.Get(AntiForgeryConfig.CookieName);
}
// If no new cookie, try and get from Request. Existing cookie is valid.
if (cookie == null || String.IsNullOrEmpty(cookie.Value))
{
if (filterContext.HttpContext.Request.Cookies.AllKeys.Contains(AntiForgeryConfig.CookieName))
{
cookie = filterContext.HttpContext.Request.Cookies.Get(AntiForgeryConfig.CookieName);
}
}
// If there's any cookie, then make a token for the header from it
if (cookie != null && !String.IsNullOrEmpty(cookie.Value))
{
string cookieToken = cookie.Value;
string formToken;
string nullToken;
AntiForgery.GetTokens(cookieToken, out nullToken, out formToken);
filterContext.HttpContext.Response.AddHeader("X-RequestVerificationToken", formToken);
}
base.OnResultExecuted(filterContext);
}
}
@3nth
Copy link
Author

3nth commented Sep 21, 2014

Useful for load testing an ASP.NET MVC app with loader.io and AntiForgeryTokens.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment