Anti-CSRF and AJAX
- prashant singh

- Jun 20, 2018
- 1 min read
The Form token is make problem for AJAX request, Ajax is send the JASON data not a HTML form because of this form token not be validated in this form. So, the solution is send the token in a custom header in HTTP. Code use Razor syntax to generate the token, and add token in AJAX request. This token is generated by calling AntiForgery.GetTokens.

string cookieToken, formToken; Antiery.GetTokens(null, out cookieToken, out formToken); var responseCookie = new HttpCookie("__AJAXAntiXsrfToken") { HttpOnly = true, Value = cookieToken }; if(FormsAuthentication.RequireSSL && HttpContext.Current.Request.IsSecureConnection) { responseCookie.Secure = true; } HttpContext.Current.Response.Cookies.Set(responseCookie); return formToken;AntiForgery.Validate method validate the tokens and throws an exception if the tokens are not valid.
void ValidateRequestHeader(HttpRequestMessage request){ string cookieToken = ""; string formToken = ""; IEnumerable<string> tokenHeaders; if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders)) { string[] tokens = tokenHeaders.First().Split(':'); if (tokens.Length == 2) { cookieToken = tokens[0].Trim(); formToken = tokens[1].Trim(); } } AntiForgery.Validate(cookieToken, formToken);}


Comments