Introduction
In modern era of web development, developers are more focused on high performance for better user experience. AJAX is one of the modern way of building web application where most of the code runs at client side and post only required data on server. Now few questions come in mind as follows:
1. Is AJAX post call is a standard practice?
2. Is AJAX call is secure? Or how we can make secure AJAX call?
3. Which one is better HTTP Post (form submit, a traditional way) or AJAX POST (a modern way)?
Background
Post back is traditional way to doing things on web application where whole page postback on form submission. In this approach most of the codes runs at sever side. AJAX is a modern way to building web application where most of the code runs at client side for better performance and user experience. In AJAX, only required data post to server instead of posting whole page.
Post back & Ajax both create HTTP request so it is not right to say one is less secure than other. In both requests attacker can inject script using CSRF (Cross-site request forgery). AJAX calls are itself protect CSRF using “Common Origin Policy” when CORS is disabled and JSONP requests are blocked.
To prevent CSRF attack one step ahead, we can implement Anti Forgery token similar to MVC framework. AJAX calls can be called from web application as well as from MVC.
In MVC, @html.antiforgerytoken() can be called on form load which store one key in hidden field and other key in cookie and using ValidateAntiForgeryToken filter, we can validate anti forgery token. The form token can be a problem for AJAX requests, because an AJAX request can send JSON data, not HTML form data. One solution is to send the tokens in a custom HTTP header.
Using the code
Sample Server side Code to generate Anti forgery token.
public static string GetAntiXsrfToken()
{
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.IsSecureConnecti on)
{
responseCookie.Secure = true;
}
HttpContext.Current.Response.Cookies.Set(responseCookie);
return formToken;
}
Sample Server side Code to validate Anti forgery token.
static void ValidateAntiXsrfToken()
{
string tokenHeader, tokenCookie;
try
{
tokenHeader = HttpContext.Current.Request.Headers.Get("__RequestVerificationToken");
var requestCookie = HttpContext.Current.Request.Cookies["__AntiXsrfToken"];
tokenCookie = requestCookie.Value;
AntiForgery.Validate(tokenCookie, tokenHeader);
}
catch
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.StatusCode = 403;
HttpContext.Current.Response.End();
}
}
Sample code to get Anti forgery token (one part) and save into hidden field.
<code><input name="__RequestVerificationToken" type="hidden" value="<%= CommonUtils.GetAntiXsrfToken() %>" /></code>
Sample client side code to pass one part to Anti Forgery token into request header from hidden field and another part will go automatically from client cookie if request is generated from same origin.
function CallServer(baseUrl, methodName, MethodArgument, callback) {
$.ajax({
type: "POST",
url: baseUrl + methodName,
data: MethodArgument,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
headers: {'__RequestVerificationToken': $("input[name='__RequestVerificationToken']").val()
},
success: function (data) {
if (callback != undefined && typeof (callback) === "function") {
callback(data.d);
}
},
error: function (data) {
if (data.status == 401 || data.status == 403)
window.location.href = "../Common/accessdenied";
else if (data.status == 419) {
displayUserMessage(commonMessage.RE_SESSIONINFO_NOT_FOUND, true);
window.location.href = "../Common/logout";
}
else
displayUserMessage(commonMessage.SERVICE_NOT_RESPONDING, true);
}
});
}
Finally, Call ValidateAntiXsrfToken() function before processing the each AJAX request at server side.
Reference
http://stackoverflow.com/questions/28405795/which-one-is-better-ajax-post-or-page-postcontroller-httppost-when-only-one-f http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attack
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet
http://stackoverflow.com/questions/39199129/is-ajax-post-an-acceptable-technique-for-changing-server-state/39205336#39205336