Created
February 18, 2015 14:18
-
-
Save peterblazejewicz/d0fab0bbb286d9cf457d to your computer and use it in GitHub Desktop.
Update AntiForgery tokens on Ajax request - both Http cookie and form tokens
This file contains 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
/// <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; | |
} |
This file contains 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
// within an action construct AJAX response and pass updated token to client | |
return Json(new | |
{ | |
stat = "ok", | |
redirectUrl = successUrl, | |
__RequestVerificationToken = UpdateRequestVerificationToken(Request) | |
}); |
This file contains 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
// 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