8 min read

In this article by Rajesh Gunasundaram, author of ASP.NET Web API Security Essentials, we will cover how to secure a Web API using forms authentication and Windows authentication. You will also get to learn the advantages and disadvantages of using the forms and Windows authentication in Web API.

In this article, we will cover the following topics:

  • The working of forms authentication
  • Implementing forms authentication in the Web API
  • Discussing the advantages and disadvantages of using the integrated Windows authentication mechanism
  • Configuring Windows authentication
  • Enabling Windows authentication in Katana
  • Discussing Hawkauthentication

(For more resources related to this topic, see here.)

The working of forms authentication

The user credentials will be submitted to the server using the HTML forms in forms authentication. This can be used in the ASP.NET Web API only if it is consumed from a web application. Forms authentication is built under ASP.NET and uses the ASP.NET membership provider to manage user accounts. Forms authentication requires a browser client to pass the user credentials to the server. It sends the user credentials in the request and uses HTTP cookies for the authentication.

Let’s list out the process of forms authenticationstep by step:

  1. The browser tries to access a restricted action that requires an authenticated request.
  2. If the browser sends an unauthenticated request, thenthe server responds with an HTTP status 302 Found and triggers the URL redirection to the login page.
  3. To send the authenticated request, the user enters the username and password and submits the form.
  4. If the credentials are valid, the server responds with an HTTP 302 status code that initiates the browser to redirect the page to the original requested URI with the authentication cookie in the response.
  5. Any request from the browser will now include the authentication cookie and the server will grant access to any restricted resource.

The following image illustrates the workflow of forms authentication:

Fig 1 – Illustrates the workflow of forms authentication

Implementing forms authentication in the Web API

To send the credentials to the server, we need an HTML form to submit. Let’s use the HTML form or view an ASP.NET MVC application.

The steps to implement forms authentication in an ASP.NET MVC application areas follows:

  1. Create New Project from the Start pagein Visual Studio.
  2. Select Visual C# Installed Templatenamed Web.
  3. Choose ASP.NET Web Applicationfrom the middle panel.
  4. Name the project Chapter06.FormsAuthentication and click OK.

    Fig 2 – We have named the ASP.NET Web Application as Chapter06.FormsAuthentication

  5. Select the MVC template in the New ASP.NET Project dialog.
  6. Tick Web APIunder Add folders and core referencesand press OKleaving Authentication to Individual User Accounts.

    Fig 3 – Select MVC template and check Web API in add folders and core references

  7. In the Models folder, add a class named Contact.cs with the following code:
    namespace Chapter06.FormsAuthentication.Models
    {
    public class Contact
       {
    publicint Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Mobile { get; set; }
       }
    }
  8. Add a Web API controller named ContactsController with the following code snippet:
    namespaceChapter06.FormsAuthentication.Api
    {
    public class ContactsController : ApiController
       {
    IEnumerable<Contact> contacts = new List<Contact>
           {
    new Contact { Id = 1, Name = "Steve", Email = "[email protected]", Mobile = "+1(234)35434" },
    new Contact { Id = 2, Name = "Matt", Email = "[email protected]", Mobile = "+1(234)5654" },
    new Contact { Id = 3, Name = "Mark", Email = "[email protected]", Mobile = "+1(234)56789" }
           };
           [Authorize]
           // GET: api/Contacts
    publicIEnumerable<Contact> Get()
           {
    return contacts;
           }
       }
    }

As you can see in the preceding code, we decorated the Get() action in ContactsController with the [Authorize] attribute. So, this Web API action can only be accessed by an authenticated request. An unauthenticated request to this action will make the browser redirect to the login page and enable the user to either register or login.

Once logged in, any request that tries to access this action will be allowed as it is authenticated.This is because the browser automatically sends the session cookie along with the request and forms authentication uses this cookie to authenticate the request.

It is very important to secure the website using SSL as forms authentication sends unencrypted credentials.

Discussing the advantages and disadvantages of using the integrated Windows authentication mechanism

First let’s see the advantages of Windows authentication. Windows authentication is built under theInternet Information Services (IIS). It doesn’t sends the user credentials along with the request. This authentication mechanism is best suited for intranet applications and doesn’t need a user to enter their credentials.

However, with all these advantages, there are a few disadvantages in the Windows authentication mechanism. It requires Kerberos that works based on tickets or NTLM, which is a Microsoft security protocols that should be supported by the client. The client’sPC must be underan active directory domain. Windows authentication is not suitable for internet applications as the client may not necessarily be on the same domain.

Configuring Windows authentication

Let’s implement Windows authentication to an ASP.NET MVC application, as follows:

  1. Create New Project from the Start pagein Visual Studio.
  2. Select Visual C# Installed Templatenamed Web.
  3. Choose ASP.NET Web Applicationfrom the middle panel.
  4. Give project name as Chapter06.WindowsAuthentication and click OK.

    Fig 4 – We have named the ASP.NET Web Application as Chapter06.WindowsAuthentication

  5. Change the Authentication mode to Windows Authentication.

    Fig 5 – Select Windows Authentication in Change Authentication window

  6. Select the MVC template in the New ASP.NET Project dialog.
  7. Tick Web API under Add folders and core references and click OK.

    Fig 6 – Select MVC template and check Web API in add folders and core references

  8. Under theModels folder, add a class named Contact.cs with the following code:
    namespace Chapter06.FormsAuthentication.Models
    {
    public class Contact
       {
    publicint Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Mobile { get; set; }
       }
    }
  9. Add a Web API controller named ContactsController with the following code:
    namespace Chapter06.FormsAuthentication.Api
    {
    public class ContactsController : ApiController
       {
    IEnumerable<Contact> contacts = new List<Contact>
           {
    new Contact { Id = 1, Name = "Steve", Email = "[email protected]", Mobile = "+1(234)35434" },
    new Contact { Id = 2, Name = "Matt", Email = "[email protected]", Mobile = "+1(234)5654" },
    new Contact { Id = 3, Name = "Mark", Email = "[email protected]", Mobile = "+1(234)56789" }
           };
           [Authorize]
           // GET: api/Contacts
    publicIEnumerable<Contact> Get()
           {
    return contacts;
           }
       }
    }

    The Get() action in ContactsController is decorated with the[Authorize] attribute. However, in Windows authentication, any request is considered as an authenticated request if the client relies on the same domain. So no explicit login process is required to send an authenticated request to call theGet() action.

Note that the Windows authentication is configured in the Web.config file:

<system.web>

<authentication mode="Windows" />

</system.web>

Enabling Windows authentication in Katana

The following steps will create a console application and enable Windows authentication in katana:

  1. Create New Project from the Start pagein Visual Studio.
  2. Select Visual C# Installed TemplatenamedWindows Desktop.
  3. Select Console Applicationfrom the middle panel.
  4. Give project name as Chapter06.WindowsAuthenticationKatana and click OK:

    Fig 7 – We have named the Console Application as Chapter06.WindowsAuthenticationKatana

  5. Install NuGet Packagenamed Microsoft.Owin.SelfHost from NuGet Package Manager:

    Fig 8 – Install NuGet Package named Microsoft.Owin.SelfHost

  6. Add aStartup class with the following code snippet:
    namespace Chapter06.WindowsAuthenticationKatana
    {
    class Startup
       {
    public void Configuration(IAppBuilder app)
           {
    var listener =
                   (HttpListener)app.Properties["System.Net.HttpListener"];
    listener.AuthenticationSchemes =
    AuthenticationSchemes.IntegratedWindowsAuthentication;
    app.Run(context =>
               {
    context.Response.ContentType = "text/plain";
    returncontext.Response.WriteAsync("Hello Packt Readers!");
               });
           }
       }
    }
  7. Add the following code in the Main function in Program.cs:
    using (WebApp.Start<Startup>("http://localhost:8001"))
    {
    Console.WriteLine("Press any Key to quit Web App.");
    Console.ReadKey();
    }
  8. Now run the application and open http://localhost:8001/ in the browser:

    Fig 8 – Open the Web App in a browser

    If you capture the request using the fiddler, you will notice an Authorization Negotiate entry in the header of the request

  9. Try calling http://localhost:8001/ in the fiddler and you will get a 401 Unauthorized response with theWWW-Authenticate headers that indicates that the server attaches a Negotiate protocol that consumes either Kerberos or NTLM, as follows:
    HTTP/1.1 401 Unauthorized
    Cache-Control: private
    Content-Type: text/html; charset=utf-8
    Server: Microsoft-IIS/8.0
    WWW-Authenticate: Negotiate
    WWW-Authenticate: NTLM
    X-Powered-By: ASP.NET
    Date: Tue, 01 Sep 2015 19:35:51 IST
    Content-Length: 6062
    Proxy-Support: Session-Based-Authentication

Discussing Hawk authentication

Hawk authentication is a message authentication code-based HTTP authentication scheme that facilitates the partial cryptographic verification of HTTP messages. Hawk authentication requires a symmetric key to be shared between the client and server.

Instead of sending the username and password to the server in order to authenticate the request, Hawk authentication uses these credentials to generate a message authentication code and is passed to the server in the request for authentication.

Hawk authentication is mainly implemented in those scenarios where you need to pass the username and password via the unsecured layer and no SSL is implemented over the server. In such cases, Hawk authentication protects the username and password and passes the message authentication code instead.

For example, if you are building a small product that has control over both the server and client and implementing SSL is too expensive for such a small project, then Hawk is the best option to secure the communication between your server and client.

Summary

Voila! We just secured our Web API using the forms- and Windows-based authentication.

In this article,youlearnedabout how forms authentication works and how it is implemented in the Web API.

You also learnedabout configuring Windows authentication and got to know about the advantages and disadvantages of using Windows authentication.

Then you learned about implementing the Windows authentication mechanism in Katana.

Finally, we had an introduction about Hawk authentication and the scenarios of using Hawk authentication.

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here