Skip to content

Instantly share code, notes, and snippets.

@peterblazejewicz
Created February 18, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterblazejewicz/d0fab0bbb286d9cf457d to your computer and use it in GitHub Desktop.
Save peterblazejewicz/d0fab0bbb286d9cf457d to your computer and use it in GitHub Desktop.
Update AntiForgery tokens on Ajax request - both Http cookie and form tokens
/// <summary>
/// resets AntiForgery validation token and update a cookie
/// The new antiforgery cookie is set as the results and sent
/// back to client with Ajax
/// </summary>
/// <param name="Request">request from current context</param>
/// <returns>string - a form token to pass to AJAX response</returns>
private string UpdateRequestVerificationToken(HttpRequestBase Request)
{
string formToken;
string cookieToken;
const string __RequestVerificationToken = "__RequestVerificationToken";
AntiForgery.GetTokens(Request.Form[__RequestVerificationToken], out cookieToken, out formToken);
if (Request.Cookies.AllKeys.Contains(__RequestVerificationToken))
{
HttpCookie cookie = Request.Cookies[__RequestVerificationToken];
cookie.HttpOnly = true;
cookie.Name = __RequestVerificationToken;
cookie.Value = cookieToken;
Response.Cookies.Add(cookie);
}
return formToken;
}
// within an action construct AJAX response and pass updated token to client
return Json(new
{
stat = "ok",
redirectUrl = successUrl,
__RequestVerificationToken = UpdateRequestVerificationToken(Request)
});
// update verification token in the form created by Ajax/Mvc
$form.find('input[name="__RequestVerificationToken"]').val(ajax.__RequestVerificationToken);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment