ASP.NET Web API and CSRF

Cross-site Request Forgery (CSRF) is typically linked to cookies. When you develop RESTful services with ASP.NET Web API, chances are likely that you are keeping away from cookies. Yet, ASP.NET Web API based services can be prone to CSRF attacks.

Say, you are consuming ASP.NET Web API from your JavaScript library and that Web API is secured by HTTP basic authentication. This setup has CSRF risk. Let’s see how this works. Implement basic authentication to your Web API. Refer to my earlier post.

Create a new action method to an existing or a new MVC controller, with view containing the code below.

@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $('#get').click(function () {
                $('#values').empty();
                $.getJSON("/yourapp/api/values", function (data) {
                    $.each(data, function (i, val) {
                        $('#values').append($('<li/>', { text: val }));
                    });
                });
            });
        });
    </script>
}
<div>
    <input id="get" type="button" value="Get" />
    <div>
        <ul id="values" />
    </div>
</div>

Since we use basic authentication, you can deploy the ASP.NET application in IIS and enable HTTPS, if you want to get as close as possible to production setup.

With that, go to the URL corresponding to the action method and view we just created. Click on Get button. Browser will popup a dialog and ask for the credentials. Enter them to see the API response getting rendered in unordered list. From this point onwards, until you close the browser, these credentials are cached and browser sends the authorization header with the credentials in all the subsequent requests to the same API.

Say you go to a page with HTML like this.

<img height="0" width="0" src="https://server/yourapp/api/values"/>

Browser is going to make the request to Web API passing in the credentials in the authorization header, without your consent/knowledge. Of course, it all boils down to GET method having no side effect but making a POST using JavaScript from a page is no big deal either. So, ASP.NET Web API can be equally vulnerable to CSRF attacks as any other Web application, whether you stay away from cookies or not.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s