Home Web Development ASP.NET Web API Security Essentials

ASP.NET Web API Security Essentials

By Rajesh Gunasundaram
books-svg-icon Book
eBook $36.99 $24.99
Print $44.99 $26.98
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $36.99 $24.99
Print $44.99 $26.98
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Setting up a Browser Client
About this book
This book incorporates the new features of ASP.NET Web API 2 that will help you to secure an ASP.NET Web API and make a well-informed decision when choosing the right security mechanism for your security requirements. We start by showing you how to set up a browser client to utilize ASP.NET Web API services. We then cover ASP.NET Web API’s security architecture, authentication, and authorization to help you secure a web API from unauthorized users. Next, you will learn how to use SSL with ASP.NET Web API, including using SSL client certificates, and integrate the ASP.NET Identity system with ASP.NET Web API. We’ll show you how to secure a web API using OAuth2 to authenticate against a membership database using OWIN middleware. You will be able to use local logins to send authenticated requests using OAuth2. We also explain how to secure a web API using forms authentication and how users can log in with their Windows credentials using integrated Windows authentication. You will come to understand the need for external authentication services to enable OAuth/OpenID and social media authentication. We’ll then help you implement anti-Cross-Site Request Forgery (CSRF) measures in ASP.NET Web API. Finally, you will discover how to enable Cross-Origin Resource Sharing (CORS) in your web API application.
Publication date:
November 2015
Publisher
Packt
Pages
152
ISBN
9781785882210

 

Chapter 1. Setting up a Browser Client

If you are reading this book, it is because you understand the importance of securing your web API. ASP.NET Web API is a framework that helps in building HTTP services that can be utilized by a wide range of clients. So it is very important to secure your Web API.

ASP.NET Web API 1.0 doesn't have any security features so the security is provided by the host such as Internet Information Server. In ASP.NET Web API 2, security features such as Katana were introduced. To secure Web API, let's understand various techniques that are involved and choose the right approach.

In this chapter, we will cover the following topics:

  • ASP.NET Web API security architecture

  • Setting up your browser client

  • Authentication and authorization

  • Implementing authentication in HTTP message handlers

  • Setting the principal

  • Using the [Authorize] Attribute

  • Custom authorization filters

  • Authorization inside a controller action

 

ASP.NET Web API security architecture


This section will give you an overview of the Web API security architecture and show you all the various extensibility points that can be used for security related things. The ASP.NET Web API security architecture is composed of three main layers. The hosting layer acts as an interface between the Web API and network stacks. The message handler pipeline layer enables implementing cross-cutting concerns such as authentication and caching. The controller handling layer is where the controllers and actions are executed, parameters are bound and validated, and HTTP response message is created. This layer also contains a filter pipeline, as shown in the following figure:

Fig 1 – This image shows the components involved in securing the Web API

Let's briefly discuss the purpose of each components in the Web API pipeline, as follows:

  • Open Web Interface for .NET (OWIN) is the new open standard hosting infrastructure. Microsoft has built its own framework called Katana on top of OWIN and all Web API security techniques such as authentication methods (for example, token-based authentication) and support for social login providers (for example, Google and Facebook) will be happening on the OWIN layer.

  • Message Handler is a class that receives an HTTP request and returns an HTTP response. Implementing authentication at message handler level is not recommended. Message handlers are used for Cross-Origin Resource Sharing (CORS).

  • Authentication Filters are guaranteed to run before the authorization filter. If you are not interested in operating your authentication logic at the OWIN layer, you can straightaway move to controllers or actions. Authentication filters are really useful to invoke OWIN-based authentication logic.

  • Authorization Filters are the places in the pipeline where you can recheck the request before the actual expensive business logic stuff runs in the model binding and validation, and the controller action is invoked.

Now that we are familiar with the security architecture, we will set up the client.

 

Setting up your browser client


Let's create a Web API for Contact Lookup. This Contact Lookup Web API service will return the list of contacts to the calling client application. Then we will be consuming the Contact Lookup service using the jQuery AJAX call to list and search contacts.

This application will help us in demonstrating the Web API security throughout this book.

Implementing Web API lookup service

In this section, we are going to create a Contact Lookup web API service that returns a list of contacts in the JavaScript Object Notation (JSON) format. The client that consumes this Contact Lookup is a simple web page that displays the list of contacts using jQuery. Follow these steps to start the project:

  1. Create New Project from the Start page in Visual Studio.

  2. Select Visual C# Installed Template named Web.

  3. Select ASP.NET Web Application in the center pane.

  4. Name the project ContactLookup and click OK, as shown in the following screenshot:

    Fig 2 – We have named the ASP.NET Web Application "ContactLookup"

  5. Select the Empty template in the New ASP.NET Project dialog box.

  6. Check Web API and click OK under Add folders and core references, as shown in the following:

    Fig 3 – We select the Empty Web API template

We just created an empty Web API project. Now let's add the required model.

Adding a model

Let's start by creating a simple model that represents a contact with the help of the following steps:

  1. First, define a simple contact model by adding a class file to the Models folder.

    Fig 4 – Right-click on the Models folder and Add a Model Class

  2. Name the class file Contact and declare properties of the Contact class.

    namespace ContactLookup.Models
    {
        public class Contact
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
            public string Mobile { get; set; }
        }
    }

We just added a model named Contact. Let's now add the required web API controller.

Adding a controller

HTTP requests are handled by controller objects in Web API. Let's define a controller with two action methods. One action to return the list of contacts and other action to return a single contact specific to a given ID:

  1. Add the Controller under the Controllers folder in Solution Explorer.

    Fig 5 – Right-click on the Controllers folder and Add a Controller

  2. Select Web API Controller – Empty and click on Add in the Add Scaffold dialog.

    Fig 6 – Select an Empty Web API Controller

  3. Let's name the controller ContactsController in the Add Controller dialog box and click Add.

    Fig 7 – Naming the controller

    This creates the ContactsController.cs file in the Controllers folder as shown in the following image:

    Fig 8 – ContactsController is added to the Controllers folder in the application

  1. Replace the code in ContactsController with the following code:

    namespace ContactLookup.Controllers
    {
        public class ContactsController : ApiController
        {
            Contact[] contacts = new Contact[] 
            { 
                new Contact { Id = 1, Name = "Steve", Email = "steve@gmail.com", Mobile = "+1(234)35434" }, 
                new Contact { Id = 2, Name = "Matt", Email = "matt@gmail.com", Mobile = "+1(234)5654" }, 
                new Contact { Id = 3, Name = "Mark", Email = "mark@gmail.com", Mobile = "+1(234)56789" } 
            };
    
            public IEnumerable<Contact> GetAllContacts()
            {
                return contacts;
            }
    
            public IHttpActionResult GetContact(int id)
            {
                var contact = contacts.FirstOrDefault(x => x.Id == id);
                if (contact == null)
                {
                    return NotFound();
                }
                return Ok(contact);
            }
        }
    }

For simplicity, contacts are stored in a fixed array inside the controller class. The controller is defined with two action methods. List of contacts will be returned by the GetAllContacts method in the JSON format and the GetContact method returns a single contact by its ID. A unique URI is applied to each method on the controller as given in the following table:

Controller Method

URI

GetAllContacts

/api/contacts

GetContact

/api/contacts/id

Consuming the Web API using JavaScript and jQuery

In this section, in order to demonstrate calling the web API with or without any security mechanisms, let's create an HTML page that consumes web API and update the page with the results using the jQuery AJAX call:

  1. In the Solution Explorer pane, right-click on the project and add New Item.

    Fig 9 – Select add new item from the context menu in Solution Explorer

  2. Create HTML Page named index.html using the Add New Item dialog.

    Fig 10 – Add an index html file by selecting HTML page in the Add New Item dialog

  3. Replace the content of the index.html file with the following code:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
      <title>Contact Lookup</title>
    </head>
    <body>
    
      <div>
        <h2>All Contacts</h2>
        <ul id="contacts" />
      </div>
      <div>
        <h2>Search by ID</h2>
        <input type="text" id="contactId" size="5" />
        <input type="button" value="Search" onclick="search();" />
        <p id="contact" />
      </div>
    
      <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
      <script>
        var uri = 'api/contacts';
    
        $(document).ready(function () {
          // Send an AJAX request
          $.getJSON(uri)
              .done(function (data) {
                // On success, 'data' contains a list of contacts.
                $.each(data, function (key, contact) {
                  // Add a list item for the contact.
                  $('<li>', { text: formatItem(contact) }).appendTo($('#contacts'));
                });
              });
        });
    
        
    function formatItem(contact) {
                return contact.Name + ', email: ' + contact.Email + ', mobile: ' + contact.Mobile;
    }
    
        function search() {
          var id = $('#contactId').val();
          $.getJSON(uri + '/' + id)
              .done(function (data) {
                $('#contact').text(formatItem(data));
              })
              .fail(function (jqXHR, textStatus, err) {
                $('#contact').text('Error: ' + err);
              });
        }
      </script>
    </body>
    </html>

Getting a list of contacts

We need to send an HTTP GET request to /api/contacts to get the list of contacts. The AJAX request is sent by the jQuery getJSON function and the array of JSON objects is received in the response. A callback function in the done function is called if the request succeeds. In the callback, we update the DOM with the contact information, as follows:

$(document).ready(function () {
      // Send an AJAX request
      $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' variable contains a list of contacts.
            $.each(data, function (key, contact) {
              // Add a list item for the contact.
              $('<li>', { text: formatItem(contact) }).appendTo($('#contacts'));
            });
          });
    });

Getting a contact by ID

To get a contact by ID, send an HTTP GET request to /api/contacts/id, where id is the contact ID.

function search() {
      var id = $('#contactId').val();
      $.getJSON(uri + '/' + id)
          .done(function (data) {
            $('#contact').text(formatItem(data));
          })
          .fail(function (jqXHR, textStatus, err) {
            $('#contact').text('Error: ' + err);
          });
    }

The request URL in getJSON has the contact ID. The response is a JSON representation of a single contact for this request.

Running the application

Start debugging the application by pressing F5. To search for a contact by ID, enter the ID and click on Search:

Fig 11 – User Interface of the Sample Browser-based Client Application

 

Authentication and authorization


We have created a simple web API that returns the list of contacts or specific contacts by ID. This web API can be accessed by any client that supports HTTP and is not secured enough. With the help of authentication and authorization mechanisms, we can secure this web API from unauthorized access.

  • Authentication mechanism helps in identifying the valid user and authenticating them using the identity of the user. Here, the identity can be a username and password.

  • Authorization mechanism helps in restricting unauthorized access to an action. For example, An unauthorized user can get the list of contacts. But he is restricted to create new contact.

Authentication

Authentication is carried out in the host Internet Information Service (IIS) for web API. Internet Information Service uses HTTP modules for authentication. We can also implement custom authentication with our own HTTP module.

The host creates a principal when it authenticates the user. Principal is an IPrincipal object that represents the security context under which the code is running. You can access the current principal from Thread.CurrentPrincipal, which is attached by the host. The user information can be accessed from the Identity object of principal. The Identity.IsAuthenticated property returns true if the user is authenticated. The Identity.IsAuthenticated will return false if the user is not authenticated.

Authorization

Authorization happens after successful authentication is provided to the controller. It helps you to grant access to resources when more granular choices are made.

For any unauthorized requests, the authorization filter returns an error response and does not allow the action to be executed. This happens as the authorization filters will be executed first before any statements in the controller action.

 

Implementing authentication in HTTP message handlers


For a self-hosted web API, the best practice is to implement authentication in an HTTP Message Handler. The principal will be set by the message handler after verifying the HTTP request. For a web API that is self-hosted, consider implementing authentication in a message handler. Otherwise, use an HTTP module instead.

The following code snippet shows an example of basic authentication implemented in an HTTP module:

public class AuthenticationHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                               CancellationToken cancellationToken)
        {
            var credentials = ParseAuthorizationHeader(request);

            if (credentials != null)
            {
                // Check if the username and passowrd in credentials are valid against the ASP.NET membership.
                // If valid, the set the current principal in the request context
                var identity = new GenericIdentity(credentials.Username);
                Thread.CurrentPrincipal = new GenericPrincipal(identity, null);;
            }

            return base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    var response = task.Result;
                    if (credentials == null && response.StatusCode == HttpStatusCode.Unauthorized)
                        Challenge(request, response);

                    return response;
                });
        }

        protected virtual Credentials ParseAuthorizationHeader(HttpRequestMessage request)
        {
            string authorizationHeader = null;
            var authorization = request.Headers.Authorization;
            if (authorization != null && authorization.Scheme == "Basic")
                authorizationHeader = authorization.Parameter;

            if (string.IsNullOrEmpty(authorizationHeader))
                return null;

            authorizationHeader = Encoding.Default.GetString(Convert.FromBase64String(authorizationHeader));

            var authenticationTokens = authorizationHeader.Split(':');
            if (authenticationTokens.Length < 2)
                return null;

            return new Credentials() { Username = authenticationTokens[0], Password = authenticationTokens[1], };
        }

        void Challenge(HttpRequestMessage request, HttpResponseMessage response)
        {
            response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", request.RequestUri.DnsSafeHost));
        }

        public class Credentials
        {
            public string Username { get; set; }
            public string Password { get; set; }
        }
    }
 

Setting the principal


If the application has the custom authentication logic implemented, then we must set the principal in two places:

  • Thread.CurrentPrincipal is the standard way to set the thread's principal in .NET.

  • HttpContext.Current.User is specific to ASP.NET.

The following code shows setting up the principal:

private void SetPrincipal(IPrincipal principal)
{
    Thread.CurrentPrincipal = principal;
    if (HttpContext.Current != null)
    {
        HttpContext.Current.User = principal;
    }
}
 

Using the [Authorize] attribute


AuthorizeAttribute will make sure if the user is authenticated or unauthenticated. Unauthorized error with HTTP status code 401 will be returned if the user is not authenticated and the corresponding action will not be invoked. Web API enables you to apply the filter in three ways. We can apply them at global level, or at the controller level, or at the individual action level.

Global authorization filter

To apply authorization filter for all Web API controllers, we need to add the AuthorizeAttribute filter to the global filter list in the Global.asax file as given below:

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}

Controller level authorization filter

To apply an authorization filter for a specific controller, we need to decorate the controller with filter attribute as given in the following code:

// Require authorization for all actions on the controller.
[Authorize]
public class ContactsController : ApiController
{
    public IEnumerable<Contact> GetAllContacts() { ... }
    public IHttpActionResult GetContact(int id) { ... }
}

Action level authorization filter

To apply an authorization filter for specific actions, we need to add the attribute to the action method as given in the following code:

public class ContactsController : ApiController
{
    public IEnumerable<Contact> GetAllContacts() { ... }

    // Require authorization for a specific action.
    [Authorize]
    public IHttpActionResult GetContact(int id) { ... }
}
 

Custom authorization filters


To implement a custom authorization filter, we need to create a class that derives either AuthorizeAttribute, AuthorizationFilterAttribute, or IAuthorizationFilter.

  • AuthorizeAttribute: An action is authorized based on the current user and the user's roles.

  • AuthorizationFilterAttribute: Synchronous authorization logic is applied and it may not be based on the current user or role.

  • IAuthorizationFilter: Both AuthorizeAttribute and AuthorizationFilterAttribute implement IAuthorizationFilter. IAuthorizationFilter is to be implemented if advanced authorization logic is required.

 

Authorization inside a controller action


Sometimes, it may be required to change the behavior after processing the request based on the principal. In such scenarios, we can implement authorization in a controller action. For example, if you would like to manipulate the response based on the user's role, we can verify the logged-in user role from the ApiController.User property in the action method itself:

public HttpResponseMessage Get()
{
    if (!User.IsInRole("Admin"))
    {
        // manipulate the response to eliminate information that shouldn't be shared with non admin users
    }
}
 

Summary


That was easy, wasn't it? We just set up the security for our APS.NET Web API that we will build upon in the upcoming chapters.

You learned about the security architecture of ASP.NET Web API that gave an overall view of what's under the hood. We then set up our browser client, from implementing the Web lookup service to calling the Web API with JavaScript and jQuery code.

You also learned about authentication and authorization techniques, which we will be covering in great detail later in the book. Moving on, you learned about HTTP Message Handlers, Principal, and the [Authorize] Attribute to control the authorization for the users.

Finally, you learned about custom authorization and authorization in a controller action to alter the behavior after processing the request based on the principal.

You learned a lot of stuff in this chapter. However, this is just the beginning. In the next chapter, you will implement a secured socket layer to the Web API. Let's get the ball rolling!

About the Author
  • Rajesh Gunasundaram

    Rajesh Gunasundaram is a software architect, technical writer and blogger. He has over 15 years of experience in the IT industry, with more than 12 years using Microsoft .NET, 2 years of BizTalk Server and a year of iOS application development. Rajesh is a founder and editor of technical blogs programmerguide and ioscorner and you can find many of his technical writings on .Net and iOS. He is also the founder and developer of VideoLens, a platform that analyses videos uploaded in Facebook pages and YouTube channels. Rajesh has also written four other books for Packt publishing. Rajesh worked on client premises located at various countries such as UK, Belarus and Norway. He also has experience in developing mobile applications for iPhone and iPad. His technical strengths include Azure, Xamarin, ASP.NET MVC, Web API, WCF, .Net Framework / .Net Core, C#, Objective-C, Angular, Bot Framework, BizTalk, SQL Server, REST, SOA, Design Patterns and Software Architecture. Rajesh is an early adopter of Angular since AngularJS. He has developed Rich interfaces using Angular, Bootstrap, HTML5 and CSS3. He has good experience in translation of designer mock-ups and wireframes into an AngularJS front-end. Good at unit testing Angular applications with Karma. Expertise in handling RESTful services in Angular. Supporting various web products developed using AngularJS and Angular.

    Browse publications by this author
Latest Reviews (3 reviews total)
ASP.NET Web API Security Essentials
Unlock this book and the full library FREE for 7 days
Start now