0

I am designing a new website and I am considering using AJAX post requests for better user experience. Is using AJAX POST requests for changing server state an acceptable design practice? Are their any security concerns in using AJAX POST requests? Is it recommended to restrict the server state changes to HTTP POST only?

EDIT

I am using ASP.NET MVC web framework for implementation.

Hemant
  • 19,486
  • 24
  • 91
  • 127

2 Answers2

2

Post, Put, Patch and Delete (although the last one is barely used) are all request types that traditionally alter the server state.

In order to answer your question, it is important to consider which framework you are using, as each one might have different best practices.

From a technical point of view, they all do practically the same, they only have different semantic meanings and conventions attached to them. If you were to use Post for everything, I doubt that anybody would complain

daniel f.
  • 1,421
  • 1
  • 13
  • 24
  • Thanks for answer. I excluded this information thinking it is not relevant but I have now updated the question. – Hemant Aug 29 '16 at 05:54
  • My question is not about GET vs POST. It's about **HTTP** POST vs **AJAX** POST. – Hemant Aug 29 '16 at 06:45
  • 1
    That is the same Thing, both are a request over the HTTP protocol. Ajax is just a technique (in which the requests are initiated by a scripting language) not a protocol. – daniel f. Aug 29 '16 at 06:51
0

Post back is traditional way to doing things on web application where whole page re-load 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. 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 request attacker can inject script using cross-site scripting (XSS) or 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, you can implement Anti Forgery token like in 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 that CSRF token. The form token can be a problem for AJAX requests, because an AJAX request might send JSON data, not HTML form data. One solution is to send the tokens in a custom HTTP header. Here is sample code snippet for more details…

Sample Server side Code to generate Anti forgery token.

/// <summary>
/// Get Anti Forgery token
/// </summary>
/// <returns></returns>
public static string GetAntiXsrfToken()
        {
            string cookieToken, formToken;
            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            var responseCookie = new HttpCookie("__AntiXsrfToken")
            {
                HttpOnly = true,
                Value = cookieToken
            };
            if (FormsAuthentication.RequireSSL &&      HttpContext.Current.Request.IsSecureConnection)
            {
                responseCookie.Secure = true;
            }
            HttpContext.Current.Response.Cookies.Set(responseCookie);

            return formToken;
        }

Sample Server side Code to validate Anti forgery token.

    /// <summary>
    /// Validate Anti Forgery token coming from secure cookie & request header
    /// </summary>
    static void ValidateAntiXsrfToken()
    {
         string tokenHeader, tokenCookie;
         try
         {
// get header token                    
tokenHeader = HttpContext.Current.Request.Headers.Get("__RequestVerificationToken");

                    // get cookie token
                    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

<input name="__RequestVerificationToken" type="hidden" value="<%= CommonUtils.GetAntiXsrfToken() %>" />

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.

You can find more details here…

Which one is better? Ajax post or page post[Controller httppost] when only one form is there in a page?

http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet

Community
  • 1
  • 1