Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Leveraging AngularJS built-in XSRF protection with ASP.NET MVC
using System.Web.Helpers;
namespace System.Web.Mvc
{
public static class HtmlExtensions
{
const string AntiForgeryCookieName = "XSRF-TOKEN";
public static IHtmlString AngularJSAntiForgeryToken(this HtmlHelper html)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
var antiForgeryCookieToken = GetCookieToken(httpContext, AntiForgeryConfig.CookieName);
var angularAntiForgeryCookieToken = GetCookieToken(httpContext, AntiForgeryCookieName);
string oldCookieToken = null;
if (!string.IsNullOrEmpty(antiForgeryCookieToken))
{
oldCookieToken = antiForgeryCookieToken;
}
string newCookieToken;
string formToken;
AntiForgery.GetTokens(oldCookieToken, out newCookieToken, out formToken);
if (string.IsNullOrEmpty(antiForgeryCookieToken) || newCookieToken != null)
{
// set default antiforgery cookie
httpContext.Response.SetCookie(new HttpCookie(AntiForgeryConfig.CookieName, newCookieToken ?? oldCookieToken)
{
HttpOnly = true,
Secure = AntiForgeryConfig.RequireSsl
});
}
if (string.IsNullOrEmpty(angularAntiForgeryCookieToken) || newCookieToken != null)
{
// set angular's specific antiforgery cookie
httpContext.Response.SetCookie(new HttpCookie(AntiForgeryCookieName, formToken)
{
HttpOnly = false,
Secure = AntiForgeryConfig.RequireSsl
});
}
return null;
}
private static string GetCookieToken(HttpContextBase httpContext, string cookieName)
{
var httpCookie = httpContext.Request.Cookies[cookieName];
if (httpCookie == null || string.IsNullOrEmpty(httpCookie.Value))
{
return null;
}
return httpCookie.Value;
}
}
}
using System.Web.Helpers;
namespace System.Web.Mvc
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ValidateAngularJSAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
const string XsrfHeaderName = "X-XSRF-TOKEN";
public void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
var cookieToken = GetCookieToken(request, AntiForgeryConfig.CookieName);
var headerToken = GetHeaderToken(request, XsrfHeaderName);
AntiForgery.Validate(cookieToken, headerToken);
}
private static string GetCookieToken(HttpRequestBase request, string cookieName)
{
var httpCookie = request.Cookies.Get(cookieName);
if (httpCookie == null || string.IsNullOrEmpty(httpCookie.Value))
{
return null;
}
return httpCookie.Value;
}
private static string GetHeaderToken(HttpRequestBase request, string headerName)
{
return request.Headers.Get(headerName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment