Click here to Skip to main content
15,885,366 members
Articles / Web Development / ASP.NET

How to make secure AJAX call

Rate me:
Please Sign up or sign in to vote.
4.95/5 (10 votes)
3 Sep 2016CPOL2 min read 57.7K   17   2
AJAX is a modern way to building web application where most of the code runs at client side for better performance and user experience. So how can we make secure AJAX call to protect from CSRF (Cross-site request forgery) attack?

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.

C#
<code>
/// <summary>
/// Get AntiForgery token
/// </summary>
/// <returns>one token into secure & HTTP only cookie & other hidden fields.</returns>
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;
}
</code>

Sample Server side Code to validate Anti forgery token.

C#
<code>/// <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();
                }
            }
</code>
Sample code to get Anti forgery token (one part) and save into hidden field.
HTML
<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.

JavaScript
<code>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);
        }
    });
}</code>

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Secure Meters Ltd.
India India
• A competent, ambitious & result oriented professional with Master degree with 12+ years of functional expertise in engineering of application software development.
• Expert in System architecture and software architecture design of high performance, high security, high availability of n-tire systems.
• Expert in web-based, n-tier and service based architecture.
• Specialized in web application level security.
• Expert in requirement analysis, designing, developing and implementing web, desktop, service & Android based mobile application.
• Proficient in communication protocols like TCP/IP, HTTP/HTTPS, SMTP, FTP/SFTP, SOAP, REST, BLE, DLMS, MQTT, Z-Wave.
• Excellent experience in process-driven software development with SDLC, SEI CMMI process and Agile methodologies.
• Strong experience in UML tool such as Enterprise Architecture.
• Solid experience in Software design & development.
• Delivered more than 7 products from concept to realization that caters to Metering, Energy monitoring, automated vehicle parking, GPS based fleet monitoring and Assisted living domains.
• Led a team of 7 members towards completion of products with planned activities.
• Strategic thinker, decision maker and deft in continually monitoring the ways for improvement of team, organizational and individual development.
• Extensive experience in Project Management, Assisted Living/home applications, IoT and intranet & internet based technologies.
• Received many rewards & awards in project executions & issue resolutions.
• Solid Analytical and Interpretation skills.

Comments and Discussions

 
QuestionHow will this protect against a malicious page that makes a csrf attack with a GET or POST call after taking anti forgery token from this web api Get token call ? Pin
Akshay Raut4-Aug-17 4:41
professionalAkshay Raut4-Aug-17 4:41 
GeneralMy vote of 5 Pin
docNyie9-Sep-16 4:08
docNyie9-Sep-16 4:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.