RESTful Day #5 - Security in Web API - Basic & Token Based Custom Authorization in Web APIs Using Action Filters

Table of Contents

  • Table of Contents
  • Introduction
  • Roadmap
  • Security in WebAPI
    • Authentication
    • Authorization
    • Maintaining Session
  • Basic Authentication
    • Pros and Cons of Basic Authentication
  • Token Based Authorization
  • WebAPI with Basic Authentication and Token Based Authorization
    • Creating User Service
      • UserServices
      • Resolve dependency of UserService
    • Implementing Basic Authentication
      • Step 1: Create generic Authentication Filter
      • Step 2: Create Basic Authentication Identity
      • Step 3: Create a Custom Authentication Filter
      • Step 4: Basic Authentication on Controller
    • Running the application
    • Design discrepancy
    • Implementing Token based Authorization
      • Set Database
      • Set Business Services
      • Setup WebAPI/Controller
      • AuthenticateController:
      • Setup Authorization Action Filter
      • Mark Controllers with Authorization filter
  • Maintaining Session using Token
  • Running the application
    • Test Authentication
    • Test Authorization
  • Conclusion
  • References
  • Other Series

Introduction


Security has always been a major concern for enterprise-level applications, especially when exposing our business through services. I have already explained a lot on WebAPI in my earlier articles of the series. I explained how to create a WebAPI, how to resolve dependencies to make it a loosely coupled design, defining custom routes and the use of attribute routing. This article will explain how to do security in a WebAPI. This article will explain how to make WebAPI secure using Basic Authentication and Token based authorization. I'll also explain how to leverage token-based authorization and Basic Authentication in WebAPI to maintain sessions in WebAPI. There is no standard way of achieving security in WebAPI. We can design our own security technique and structure that suits our application best.

Roadmap

The following is the roadmap I have setup to learn WebAPI step-by-step:

roadmap
 
I'll intentionally use Visual Studio 2010 and .NET Framework 4.0 because there are a few implementations that are very hard to find in .NET Framework 4.0, but I'll make it easy by showing how to do it.

Security in WebAPI


Security in itself is a very complicated and tricky topic. I'll try to explain how to do it in WebAPI in my own way. When we plan to create an enterprise-level application, we especially want to take care of authentication and authorization. These are two techniques that, if used well, makes our application secure, in our case makes our WebAPI more secure.

safety

Image credit: pixabay.

Authentication

Authentication is all about the identity of the end user. It's about validating the identity of a user who is accessing our system, that he is authenticated enough to use our resources or not. Does that end user have valid credentials to log into our system? Credentials can be in the form of a user name and word. We'll use the Basic Authentication technique to understand how to do authentication in WebAPI.

Authorization

Authorization should be considered as a second step after authentication to do security. Authorization means what all the permissions are that the authenticated user must have to access web resources. Are they allowed to access/perform an action on that resource? This could be done by setting roles and permissions for an end-user who is authenticated, or can be done by providing a secure token, using which an end user can have access to other services or resources.

Maintaining Session

RESTful services work on a stateless protocol, in other words HTTP. We can maintain sessions in the Web API using token-based authorization techniques. An authenticated user will be allowed to access resources for a specific period of time and can re-instantiate the request with an increased session time delta to access other resource or the same resource. Websites using WebAPIs as RESTful services may need to implement login/logout for a user, to maintain sessions for the user, to provide roles and permissions to their user, all these features could be done using basic authentication and token-based authorization. I'll explain this step-by-step.

Basic Authentication


Basic authentication is a mechanism, where an end user is authenticated using our service, in other words RESTful service, using plain credentials such as user name and word. An end user makes a request to the service for authentication with the user name and word embedded in the request header. The service receives the request and checks if the credentials are valid or not and returns the response accordingly, in case of invalid credentials, the service responds with a 401 error code, in other words unauthorized. The actual credentials by which the comparison is done may lie in the database, any config file like web.config or in the code itself.

Pros and Cons of Basic Authentication

Basic authentication has its own pros and cons. It is advantageous for implementation, it is very easy to implement, it is supported by nearly all the modern browsers and has become an authentication standard in RESTful / Web APIs. It has the disadvantages of sending user credentials in plain text, sending user credentials inside a request header, in other words prone to hack. One must send credentials each time a service is called. No session is maintained and a user cannot logout once logged in using basic authentication. It is very prone to Cross-Site Request Forgery (CSRF).

Token Based Authorization


The authorization part comes just after authentication. Once authenticated, a service can send a token to an end user by which the user can access other resources. The token could be any encrypted key that only the server/service understands and when it fetches the token from the request made by the end user, it validates the token and authorizes the user into the system. The token generated could be stored in a database or an external file as well, in other words we need to persist the token for future references. The token can have its own lifetime and may expire accordingly. In that case the user will need to be authenticated again into the system.

WebAPI with Basic Authentication and Token Based Authorization


Token Based Authorization

Creating User Service

Just open your WebAPI project or the WebAPI project that we discussed in the last part of learning WebAPI.

web api

We have BusinessEntities, BusinessServices, DataModel, DependencyResolver and a WebAPI project as well. We already have a User table in the database, or you can create your own database with a table like User Table as shown below.

User Table

I am using a WebAPI database, I have attached the scripts for download.

UserServices

Go to BusinessServices project and add a new interface, IUserService, and a service named UserServices implementing that interface as in the following:

IUserService

insert face

Just define one method named Authenticate in the interface.
  1. namespace BusinessServices  
  2. {  
  3.    public interface IUserServices  
  4.    {  
  5.       int Authenticate(string userName, string word);  
  6.    }  
  7. }  
This method takes username and word as a parameter and returns the specific userId if the user is authenticated successfully.

Just implement this method in the UserServices class, just like we created services earlier in the series.
  1. using DataModel.UnitOfWork;  
  2.   
  3. namespace BusinessServices {  
  4.     /// <summary>  
  5.     /// Offers services for user specific operations  
  6.     /// </summary>  
  7.     public class UserServices: IUserServices {  
  8.         private readonly UnitOfWork _unitOfWork;  
  9.   
  10.         /// <summary>  
  11.         /// Public constructor.  
  12.         /// </summary>  
  13.         public UserServices(UnitOfWork unitOfWork) {  
  14.             _unitOfWork = unitOfWork;  
  15.         }  
  16.   
  17.         /// <summary>  
  18.         /// Public method to authenticate user by user name and word.  
  19.         /// </summary>  
  20.         /// <param name="userName"></param>  
  21.         /// <param name="word"></param>  
  22.         /// <returns></returns>  
  23.         public int Authenticate(string userName, string word) {  
  24.             var user = _unitOfWork.UserRepository.Get(u = > u.UserName == userName && u.word == word);  
  25.             if (user != null && user.UserId > 0) {  
  26.                 return user.UserId;  
  27.             }  
  28.             return 0;  
  29.         }  
  30.     }  
  31. }  
You can clearly see that Authenticate method just checks the user credentials from UserRepository and returns the values accordingly. The code is very self-explanatory.

Resolve dependency of UserService

Just open the DependencyResolver class in the BusinessServices project itself and add its dependency type so that we get the UserServices dependency resolved at run time, so add,
  1. registerComponent.RegisterType<IUserServices, UserServices>();  
line to SetUP method. Our class becomes:
  1. using System.ComponentModel.Composition;  
  2. using DataModel;  
  3. using DataModel.UnitOfWork;  
  4. using Resolver;  
  5.   
  6. namespace BusinessServices {  
  7.     [Export(typeof(IComponent))]  
  8.     public class DependencyResolver: IComponent {  
  9.         public void SetUp(IRegisterComponent registerComponent) {  
  10.             registerComponent.RegisterType < IProductServices, ProductServices > ();  
  11.             registerComponent.RegisterType < IUserServices, UserServices > ();  
  12.         }  
  13.     }  
  14. }  
Implementing Basic Authentication

Step 1: Create a generic Authentication Filter

Add a folder named Filters to the WebAPI project and add a class named GenericAuthenticationFilter under that folder. Derive that class from AuthorizationFilterAttribute, this is a class under System.Web.Http.Filters.

I have created the generic authentication filter that will be like:
  1. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]  
  2. public class GenericAuthenticationFilter: AuthorizationFilterAttribute {  
  3.   
  4.     /// <summary>  
  5.     /// Public default Constructor  
  6.     /// </summary>  
  7.     public GenericAuthenticationFilter() {}  
  8.   
  9.     private readonly bool _isActive = true;  
  10.   
  11.     /// <summary>  
  12.     /// parameter isActive explicitly enables/disables this filetr.  
  13.     /// </summary>  
  14.     /// <param name="isActive"></param>  
  15.     public GenericAuthenticationFilter(bool isActive) {  
  16.         _isActive = isActive;  
  17.     }  
  18.   
  19.     /// <summary>  
  20.     /// Checks basic authentication request  
  21.     /// </summary>  
  22.     /// <param name="filterContext"></param>  
  23.     public override void OnAuthorization(HttpActionContext filterContext) {  
  24.         if (!_isActive) return;  
  25.         var identity = FetchAuthHeader(filterContext);  
  26.         if (identity == null) {  
  27.             ChallengeAuthRequest(filterContext);  
  28.             return;  
  29.         }  
  30.         var genericPrincipal = new GenericPrincipal(identity, null);  
  31.         Thread.CurrentPrincipal = genericPrincipal;  
  32.         if (!OnAuthorizeUser(identity.Name, identity.word, filterContext)) {  
  33.             ChallengeAuthRequest(filterContext);  
  34.             return;  
  35.         }  
  36.         base.OnAuthorization(filterContext);  
  37.     }  
  38.   
  39.     /// <summary>  
  40.     /// Virtual method.Can be overriden with the custom Authorization.  
  41.     /// </summary>  
  42.     /// <param name="user"></param>  
  43.     /// <param name=""></param>  
  44.     /// <param name="filterContext"></param>  
  45.     /// <returns></returns>  
  46.     protected virtual bool OnAuthorizeUser(string user, string , HttpActionContext filterContext) {  
  47.         if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty()) return false;  
  48.         return true;  
  49.     }  
  50.   
  51.     /// <summary>  
  52.     /// Checks for autrhorization header in the request and parses it, creates user credentials and returns as BasicAuthenticationIdentity  
  53.     /// </summary>  
  54.     /// <param name="filterContext"></param>  
  55.     protected virtual BasicAuthenticationIdentity FetchAuthHeader(HttpActionContext filterContext) {  
  56.         string authHeaderValue = null;  
  57.         var authRequest = filterContext.Request.Headers.Authorization;  
  58.         if (authRequest != null && !String.IsNullOrEmpty(authRequest.Scheme) && authRequest.Scheme == "Basic") authHeaderValue = authRequest.Parameter;  
  59.         if (string.IsNullOrEmpty(authHeaderValue)) return null;  
  60.         authHeaderValue = Encoding.Default.GetString(Convert.FromBase64String(authHeaderValue));  
  61.         var credentials = authHeaderValue.Split(':');  
  62.         return credentials.Length < 2 ? null : new BasicAuthenticationIdentity(credentials[0], credentials[1]);  
  63.     }  
  64.   
  65.   
  66.     /// <summary>  
  67.     /// Send the Authentication Challenge request  
  68.     /// </summary>  
  69.     /// <param name="filterContext"></param>  
  70.     private static void ChallengeAuthRequest(HttpActionContext filterContext) {  
  71.         var dnsHost = filterContext.Request.RequestUri.DnsSafeHost;  
  72.         filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
  73.         filterContext.Response.Headers.Add("WWW-Authenticate"string.Format("Basic realm=\"{0}\"", dnsHost));  
  74.     }  
  75. }  
Since this is an AuthorizationFilter derived class, we need to override its methods to add our custom logic. Here the “OnAuthorization” method is overridden to add a custom logic. Whenever we get an ActionContext on OnAuthorization, we'll check for its header, since we are pushing our service to use BasicAuthentication, the request headers should contain this information. I have used FetchAuthHeader to check the scheme, if it comes to be “Basic” and thereafter stores the credentials, in other words user name and word, in a form of an object of class BasicAuthenticationIdentity, therefore creating an identity out of valid credentials.
  1. protected virtual BasicAuthenticationIdentity FetchAuthHeader(HttpActionContext filterContext) {  
  2.     string authHeaderValue = null;  
  3.     var authRequest = filterContext.Request.Headers.Authorization;  
  4.     if (authRequest != null && !String.IsNullOrEmpty(authRequest.Scheme) && authRequest.Scheme == "Basic") authHeaderValue = authRequest.Parameter;  
  5.     if (string.IsNullOrEmpty(authHeaderValue)) return null;  
  6.     authHeaderValue = Encoding.Default.GetString(Convert.FromBase64String(authHeaderValue));  
  7.     var credentials = authHeaderValue.Split(':');  
  8.     return credentials.Length < 2 ? null : new BasicAuthenticationIdentity(credentials[0], credentials[1]);  
  9. }  
I am expecting values to be encrypted using Base64 string. You can use your own encryption mechanism as well.

Later on in the OnAuthorization method we create a genericPrincipal with the created identity and assign it to the current Thread principal as in the following:
  1. var genericPrincipal = new GenericPrincipal(identity, null);  
  2. Thread.CurrentPrincipal = genericPrincipal;  
  3. if (!OnAuthorizeUser(identity.Name, identity.word, filterContext))  
  4. {  
  5.    ChallengeAuthRequest(filterContext);  
  6.    return;  
  7. }  
  8. base.OnAuthorization(filterContext);  
Once done, a challenge to that request is added, where we add a response and tell the Basic realm:

filterContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", dnsHost));
in ChallengeAuthRequest method.

If no credentials is provided in the request, this generic authentication filter sets the generic authentication principal to the current thread principal.

Since we understand the drawback that in basic authentication credentials are ed in plain text, it would be good if our service uses SSL for communication or message ing.

We have an overridden constructor as well that allows the default behavior of the filter to be stopped by just ing in a parameter, in other words true or false.
  1. public GenericAuthenticationFilter(bool isActive)  
  2. {  
  3.    _isActive = isActive;  
  4. }  
We can use OnAuthorizeUser for custom authorization purposes.

Step 2: Create a Basic Authentication Identity

Before we proceed further, we also need the BasicIdentity class, that takes credentials and assigns them to the Generic Principal. So just add one more class named BasicAuthenticationIdentity deriving from GenericIdentity.

This class contains the three properties UserName, word and UserId. I intentionally added UserId because we'll need that in the future. So our class will be like:
  1. using System.Security.Principal;  
  2.   
  3. namespace WebAPI.Filters {  
  4.     /// <summary>  
  5.     /// Basic Authentication identity  
  6.     /// </summary>  
  7.     public class BasicAuthenticationIdentity: GenericIdentity {  
  8.         /// <summary>  
  9.         /// Get/Set for word  
  10.         /// </summary>  
  11.         public string word {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         /// <summary>  
  16.         /// Get/Set for UserName  
  17.         /// </summary>  
  18.         public string UserName {  
  19.             get;  
  20.             set;  
  21.         }  
  22.         /// <summary>  
  23.         /// Get/Set for UserId  
  24.         /// </summary>  
  25.         public int UserId {  
  26.             get;  
  27.             set;  
  28.         }  
  29.   
  30.         /// <summary>  
  31.         /// Basic Authentication Identity Constructor  
  32.         /// </summary>  
  33.         /// <param name="userName"></param>  
  34.         /// <param name="word"></param>  
  35.         public BasicAuthenticationIdentity(string userName, string word): base(userName, "Basic") {  
  36.             word = word;  
  37.             UserName = userName;  
  38.         }  
  39.     }  
  40. }  
Step 3: Create a Custom Authentication Filter

Now you are ready to use your own Custom Authentication filter. Just add one more class under that Filters project and call it APIAuthenticationFilter, this class will derive from GenericAuthenticationFilter, that we created in the first step.This class overrides the OnAuthorizeUser method to add custom logic for authenticating a request. It uses UserService that we created earlier to check the user.
  1. protected override bool OnAuthorizeUser(string username, string word, HttpActionContext actionContext) {  
  2.     var provider = actionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(IUserServices)) as IUserServices;  
  3.     if (provider != null) {  
  4.         var userId = provider.Authenticate(username, word);  
  5.         if (userId > 0) {  
  6.             var basicAuthenticationIdentity = Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;  
  7.             if (basicAuthenticationIdentity != null) basicAuthenticationIdentity.UserId = userId;  
  8.             return true;  
  9.         }  
  10.     }  
  11.     return false;  
  12. }  
Complete class
  1. using System.Threading;  
  2. using System.Web.Http.Controllers;  
  3. using BusinessServices;  
  4.   
  5. namespace WebAPI.Filters {  
  6.     /// <summary>  
  7.     /// Custom Authentication Filter Extending basic Authentication  
  8.     /// </summary>  
  9.     public class APIAuthenticationFilter: GenericAuthenticationFilter {  
  10.         /// <summary>  
  11.         /// Default Authentication Constructor  
  12.         /// </summary>  
  13.         public APIAuthenticationFilter() {}  
  14.   
  15.         /// <summary>  
  16.         /// AuthenticationFilter constructor with isActive parameter  
  17.         /// </summary>  
  18.         /// <param name="isActive"></param>  
  19.         public APIAuthenticationFilter(bool isActive): base(isActive) {}  
  20.   
  21.         /// <summary>  
  22.         /// Protected overriden method for authorizing user  
  23.         /// </summary>  
  24.         /// <param name="username"></param>  
  25.         /// <param name="word"></param>  
  26.         /// <param name="actionContext"></param>  
  27.         /// <returns></returns>  
  28.         protected override bool OnAuthorizeUser(string username, string word, HttpActionContext actionContext) {  
  29.             var provider = actionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(IUserServices)) as IUserServices;  
  30.             if (provider != null) {  
  31.                 var userId = provider.Authenticate(username, word);  
  32.                 if (userId > 0) {  
  33.                     var basicAuthenticationIdentity = Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;  
  34.                     if (basicAuthenticationIdentity != null) basicAuthenticationIdentity.UserId = userId;  
  35.                     return true;  
  36.                 }  
  37.             }  
  38.             return false;  
  39.         }  
  40.     }  
  41. }  
Step 4: Basic Authentication on the Controller

Since we already have our products controller as in the following:
  1. public class ProductController: APIController {#region Private variable.  
  2.   
  3.     private readonly IProductServices _productServices;  
  4.  
  5.     #endregion  
  6.  
  7.     #region Public Constructor  
  8.   
  9.     /// <summary>  
  10.     /// Public constructor to initialize product service instance  
  11.     /// </summary>  
  12.     public ProductController(IProductServices productServices) {  
  13.         _productServices = productServices;  
  14.     }  
  15.  
  16.     #endregion  
  17.   
  18.     // GET API/product  
  19.     [GET("allproducts")]  
  20.     [GET("all")]  
  21.     public HttpResponseMessage Get() {  
  22.         var products = _productServices.GetAllProducts();  
  23.         var productEntities = products as List < ProductEntity > ? ? products.ToList();  
  24.         if (productEntities.Any()) return Request.CreateResponse(HttpStatusCode.OK, productEntities);  
  25.         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");  
  26.     }  
  27.   
  28.     // GET API/product/5  
  29.     [GET("productid/{id?}")]  
  30.     [GET("particularproduct/{id?}")]  
  31.     [GET("myproduct/{id:range(1, 3)}")]  
  32.     public HttpResponseMessage Get(int id) {  
  33.         var product = _productServices.GetProductById(id);  
  34.         if (product != nullreturn Request.CreateResponse(HttpStatusCode.OK, product);  
  35.         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");  
  36.     }  
  37.   
  38.     // POST API/product  
  39.     [POST("Create")]  
  40.     [POST("Register")]  
  41.     public int Post([FromBody] ProductEntity productEntity) {  
  42.         return _productServices.CreateProduct(productEntity);  
  43.     }  
  44.   
  45.     // PUT API/product/5  
  46.     [PUT("Update/productid/{id}")]  
  47.     [PUT("Modify/productid/{id}")]  
  48.     public bool Put(int id, [FromBody] ProductEntity productEntity) {  
  49.         if (id > 0) {  
  50.             return _productServices.UpdateProduct(id, productEntity);  
  51.         }  
  52.         return false;  
  53.     }  
  54.   
  55.     // DELETE API/product/5  
  56.     [DELETE("remove/productid/{id}")]  
  57.     [DELETE("clear/productid/{id}")]  
  58.     [PUT("delete/productid/{id}")]  
  59.     public bool Delete(int id) {  
  60.         if (id > 0) return _productServices.DeleteProduct(id);  
  61.         return false;  
  62.     }  
  63. }  
There are three ways in which you can use this authentication filter.

Just apply this filer to ProductController. You can add this filter at the top of the controller, for all API requests to be validated as in the following:
  1. [APIAuthenticationFilter]  
  2. [RoutePrefix("v1/Products/Product")]  
  3. public class ProductController : APIController  
You can also globally add this in Web API configuration file, so that that filter applies to all the controllers and all the actions associated with it.

GlobalConfiguration.Configuration.Filters.Add(new APIAuthenticationFilter());

You can also apply it to the Action level too if you wish to apply or not apply authentication to that action.
  1. // GET API/product  
  2. [APIAuthenticationFilter(true)]  
  3. [GET("allproducts")]  
  4. [GET("all")]  
  5. public HttpResponseMessage Get()   
  6. {…………………  
  7. }  
  8.   
  9. // GET API/product/5  
  10. [APIAuthenticationFilter(false)]  
  11. [GET("productid/{id?}")]  
  12. [GET("particularproduct/{id?}")]  
  13. [GET("myproduct/{id:range(1, 3)}")]  
  14. public HttpResponseMessage Get(int id)   
  15. {……………………..  
  16. }  
Running the application

We have already implemented Basic Authentication, just try to run the application to test if it is working.

Just run the application, we get:

Just run the application

We already have our test client added, but for new readers, just go to Manage Nuget Packages, by right-clicking WebAPI project and type WebAPITestClient into the searchbox in online packages as in the following:

WebAPI

You'll get “A simple Test Client for ASP.NET Web API”, just add it. You'll get a help controller in Areas -> HelpPage as shown below.

HelpPage

I have already provided the database scripts and data in my previous article, you can use that.

Append “/help” to the application URL and you'll get the test client.

GET

GET

POST

POST

PUT

PUT

DELETE

DELETE

You can test each service by clicking on it. Once you click on the service link, you'll be redirected to test the service page of that specific service. On that page there is a button Test API in the right bottom corner, just press that button to test your service.

test api

Service to Get All the products.

Service for Get All products

When you click on the Send request, a dialog will be shown asking for Authentication. Just cancel that dialog and let the request go without credentials. You'll get a response of Unauthorized, in other words 401.

response of Unauthorized

This means our authentication mechanism is working.

authentication mechanism

Just to double check it, let's send the request with credentials now. Just add a header too with the request. The header should be like:

Authorization: Basic YWtoaWw6YWtoaWw=

Here “YWtoaWw6YWtoaWw=” is my Base64 encoded user name and word, in other words akhil:akhil.

Header

Click on Send and we get the response as desired.

get the response

Authentication

Likewise you can test all the service endpoints.

This means our service is working with Basic Authentication.

Design discrepancy

This design, when running on SSL, is very good for implementing Basic Authentication. But there are a few scenarios in which, along with Basic Authentication, I would like to leverage authorization too and not even authorization but sessions too. When we talk about creating an enterprise application, it just do not limit things to securing our endpoints with authentication only.

In this design, I'll need to send a user name and word each time with every request. Assume I want to create an application where authentication only occurs only once as my login is done and after successfully authentication, in other words logging in, I must be able to use other services of that application. In other words I am then authorized to use those services. Our application should be robust enough that it restricts even authenticated users from using other services he is not authorized for. Yes, I am talking about Token-based authorization.

I'll expose only one endpoint for authentication and that will be my login service. So the client only knows about that login service that needs credentials to get logged into the system.

After the client successfully logs in I'll send a token that could be a GUID or an encrypted key by any xyz algorithm that I want when the user makes a request for any other services after login, should provide this token along with that request. And to maintain sessions, our token will have an expiry too, that will last for 15 minutes, that can be made configurable using a web.config file. After the session expires, the user will be logged out and will again need to use the login service with credentials to get a new token. Seems exciting to me, let's implement this.

Implementing Token based Authorization

To overcome the preceding scenarios, let's start developing and give our application the shape of a thick client enterprise architecture.

lock

Set Database

Let's start with setting up a database. When we see our previously created database that we had set up in the first part of the series, we have a token table. We require this token table for token persistence. Our token will persist in the database with an expiry time. If you are using your own database, you can create a token table as in the following:

Set Database

Set Business Services

Just navigate to BusinessServices and create one more Interface named ITokenServices for the token-based operations as in the following:
  1. using BusinessEntities;  
  2.   
  3. namespace BusinessServices {  
  4.     public interface ITokenServices {#region Interface member methods.  
  5.         /// <summary>  
  6.         /// Function to generate unique token with expiry against the provided userId.  
  7.         /// Also add a record in database for generated token.  
  8.         /// </summary>  
  9.         /// <param name="userId"></param>  
  10.         /// <returns></returns>  
  11.         TokenEntity GenerateToken(int userId);  
  12.   
  13.         /// <summary>  
  14.         /// Function to validate token againt expiry and existance in database.  
  15.         /// </summary>  
  16.         /// <param name="tokenId"></param>  
  17.         /// <returns></returns>  
  18.         bool ValidateToken(string tokenId);  
  19.   
  20.         /// <summary>  
  21.         /// Method to kill the provided token id.  
  22.         /// </summary>  
  23.         /// <param name="tokenId"></param>  
  24.         bool Kill(string tokenId);  
  25.   
  26.         /// <summary>  
  27.         /// Delete tokens for the specific deleted user  
  28.         /// </summary>  
  29.         /// <param name="userId"></param>  
  30.         /// <returns></returns>  
  31.         bool DeleteByUserId(int userId);#endregion  
  32.     }  
  33. }  
We have four methods defined in this interface. Let's create a TokenServices class that implements ITokenServices and understand each method.

The GenerateToken method takes a userId as a parameter and generates a token, encapsulates that token in a token entity with a Token expiry time and returns it to the caller.
  1. public TokenEntity GenerateToken(int userId) {  
  2.     string token = Guid.NewGuid().ToString();  
  3.     DateTime issuedOn = DateTime.Now;  
  4.     DateTime expiredOn = DateTime.Now.AddSeconds(  
  5.     Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));  
  6.     var tokendomain = new Token {  
  7.         UserId = userId,  
  8.         AuthToken = token,  
  9.         IssuedOn = issuedOn,  
  10.         ExpiresOn = expiredOn  
  11.     };  
  12.   
  13.     _unitOfWork.TokenRepository.Insert(tokendomain);  
  14.     _unitOfWork.Save();  
  15.     var tokenModel = new TokenEntity() {  
  16.         UserId = userId,  
  17.         IssuedOn = issuedOn,  
  18.         ExpiresOn = expiredOn,  
  19.         AuthToken = token  
  20.     };  
  21.   
  22.     return tokenModel;  
  23. }  
When generating a token, it names a database entry into the Token table.

The ValidateToken method just validates that the token associated with the request is valid or not, in other words it exists in the database within its expiry time limit.
  1. public bool ValidateToken(string tokenId) {  
  2.     var token = _unitOfWork.TokenRepository.Get(t = > t.AuthToken == tokenId && t.ExpiresOn > DateTime.Now);  
  3.     if (token != null && !(DateTime.Now > token.ExpiresOn)) {  
  4.         token.ExpiresOn = token.ExpiresOn.AddSeconds(  
  5.         Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));  
  6.         _unitOfWork.TokenRepository.Update(token);  
  7.         _unitOfWork.Save();  
  8.         return true;  
  9.     }  
  10.     return false;  
  11. }  
It just takes the token Id supplied in the request.

Kill Token just kills the token, in other words removes the token from the database.
  1. public bool Kill(string tokenId) {  
  2.     _unitOfWork.TokenRepository.Delete(x = > x.AuthToken == tokenId);  
  3.     _unitOfWork.Save();  
  4.     var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x = > x.AuthToken == tokenId).Any();  
  5.     if (isNotDeleted) {  
  6.         return false;  
  7.     }  
  8.     return true;  
  9. }  
The DeleteByUserId method deletes all the token entries from the database w.r.t specific userId associated with those tokens.
  1. public bool DeleteByUserId(int userId)  
  2. {  
  3.    _unitOfWork.TokenRepository.Delete(x => x.UserId == userId);  
  4.    _unitOfWork.Save();  
  5.   
  6.    var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x => x.UserId == userId).Any();  
  7.    return !isNotDeleted;  
  8. }  
So with _unitOfWork and along with Constructor our class becomes:
  1. using System;  
  2. using System.Configuration;  
  3. using System.Linq;  
  4. using BusinessEntities;  
  5. using DataModel;  
  6. using DataModel.UnitOfWork;  
  7.   
  8. namespace BusinessServices {  
  9.     public class TokenServices: ITokenServices {#region Private member variables.  
  10.         private readonly UnitOfWork _unitOfWork;#endregion  
  11.  
  12.         #region Public constructor.  
  13.         /// <summary>  
  14.         /// Public constructor.  
  15.         /// </summary>  
  16.         public TokenServices(UnitOfWork unitOfWork) {  
  17.             _unitOfWork = unitOfWork;  
  18.         }#endregion  
  19.  
  20.  
  21.         #region Public member methods.  
  22.   
  23.         /// <summary>  
  24.         /// Function to generate unique token with expiry against the provided userId.  
  25.         /// Also add a record in database for generated token.  
  26.         /// </summary>  
  27.         /// <param name="userId"></param>  
  28.         /// <returns></returns>  
  29.         public TokenEntity GenerateToken(int userId) {  
  30.             string token = Guid.NewGuid().ToString();  
  31.             DateTime issuedOn = DateTime.Now;  
  32.             DateTime expiredOn = DateTime.Now.AddSeconds(  
  33.             Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));  
  34.             var tokendomain = new Token {  
  35.                 UserId = userId,  
  36.                 AuthToken = token,  
  37.                 IssuedOn = issuedOn,  
  38.                 ExpiresOn = expiredOn  
  39.             };  
  40.   
  41.             _unitOfWork.TokenRepository.Insert(tokendomain);  
  42.             _unitOfWork.Save();  
  43.             var tokenModel = new TokenEntity() {  
  44.                 UserId = userId,  
  45.                 IssuedOn = issuedOn,  
  46.                 ExpiresOn = expiredOn,  
  47.                 AuthToken = token  
  48.             };  
  49.   
  50.             return tokenModel;  
  51.         }  
  52.   
  53.         /// <summary>  
  54.         /// Method to validate token against expiry and existence in database.  
  55.         /// </summary>  
  56.         /// <param name="tokenId"></param>  
  57.         /// <returns></returns>  
  58.         public bool ValidateToken(string tokenId) {  
  59.             var token = _unitOfWork.TokenRepository.Get(t = > t.AuthToken == tokenId && t.ExpiresOn > DateTime.Now);  
  60.             if (token != null && !(DateTime.Now > token.ExpiresOn)) {  
  61.                 token.ExpiresOn = token.ExpiresOn.AddSeconds(  
  62.                 Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));  
  63.                 _unitOfWork.TokenRepository.Update(token);  
  64.                 _unitOfWork.Save();  
  65.                 return true;  
  66.             }  
  67.             return false;  
  68.         }  
  69.   
  70.         /// <summary>  
  71.         /// Method to kill the provided token id.  
  72.         /// </summary>  
  73.         /// <param name="tokenId">true for successful delete</param>  
  74.         public bool Kill(string tokenId) {  
  75.             _unitOfWork.TokenRepository.Delete(x = > x.AuthToken == tokenId);  
  76.             _unitOfWork.Save();  
  77.             var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x = > x.AuthToken == tokenId).Any();  
  78.             if (isNotDeleted) {  
  79.                 return false;  
  80.             }  
  81.             return true;  
  82.         }  
  83.   
  84.         /// <summary>  
  85.         /// Delete tokens for the specific deleted user  
  86.         /// </summary>  
  87.         /// <param name="userId"></param>  
  88.         /// <returns>true for successful delete</returns>  
  89.         public bool DeleteByUserId(int userId) {  
  90.             _unitOfWork.TokenRepository.Delete(x = > x.UserId == userId);  
  91.             _unitOfWork.Save();  
  92.   
  93.             var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x = > x.UserId == userId).Any();  
  94.             return !isNotDeleted;  
  95.         }  
  96.  
  97.         #endregion  
  98.     }  
  99. }  
Do not forget to resolve the dependency of this Token service in the DependencyResolver class. Add registerComponent.RegisterType<ITokenServices, TokenServices>(); to the SetUp method of the DependencyResolver class in the BusinessServices project.
  1. [Export(typeof(IComponent))]  
  2. public class DependencyResolver: IComponent {  
  3.     public void SetUp(IRegisterComponent registerComponent) {  
  4.         registerComponent.RegisterType < IProductServices, ProductServices > ();  
  5.         registerComponent.RegisterType < IUserServices, UserServices > ();  
  6.         registerComponent.RegisterType < ITokenServices, TokenServices > ();  
  7.   
  8.     }  
  9. }  
Setup WebAPI/Controller

Now since we decided that we don't want authentication to be applied on each and every API exposed, I'll create a single Controller/API endpoint that takes authentication or a login request and uses a Token Service to generate a token and respond client/caller with a token that persists in the database with expiry details.

Add a new Controller under the Controllers folder in the WebAPI with the name Authenticate as in the following:

Add a new Controller

AuthenticateController
  1. using System.Configuration;  
  2. using System.Net;  
  3. using System.Net.Http;  
  4. using System.Web.Http;  
  5. using AttributeRouting.Web.Http;  
  6. using BusinessServices;  
  7. using WebAPI.Filters;  
  8.   
  9. namespace WebAPI.Controllers {  
  10.     [APIAuthenticationFilter]  
  11.     public class AuthenticateController: APIController {#region Private variable.  
  12.   
  13.         private readonly ITokenServices _tokenServices;  
  14.  
  15.         #endregion  
  16.  
  17.         #region Public Constructor  
  18.   
  19.         /// <summary>  
  20.         /// Public constructor to initialize product service instance  
  21.         /// </summary>  
  22.         public AuthenticateController(ITokenServices tokenServices) {  
  23.             _tokenServices = tokenServices;  
  24.         }  
  25.  
  26.         #endregion  
  27.   
  28.         /// <summary>  
  29.         /// Authenticates user and returns token with expiry.  
  30.         /// </summary>  
  31.         /// <returns></returns>  
  32.         [POST("login")]  
  33.         [POST("authenticate")]  
  34.         [POST("get/token")]  
  35.         public HttpResponseMessage Authenticate() {  
  36.             if (System.Threading.Thread.CurrentPrincipal != null && System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated) {  
  37.                 var basicAuthenticationIdentity = System.Threading.Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;  
  38.                 if (basicAuthenticationIdentity != null) {  
  39.                     var userId = basicAuthenticationIdentity.UserId;  
  40.                     return GetAuthToken(userId);  
  41.                 }  
  42.             }  
  43.             return null;  
  44.         }  
  45.   
  46.         /// <summary>  
  47.         /// Returns auth token for the validated user.  
  48.         /// </summary>  
  49.         /// <param name="userId"></param>  
  50.         /// <returns></returns>  
  51.         private HttpResponseMessage GetAuthToken(int userId) {  
  52.             var token = _tokenServices.GenerateToken(userId);  
  53.             var response = Request.CreateResponse(HttpStatusCode.OK, "Authorized");  
  54.             response.Headers.Add("Token", token.AuthToken);  
  55.             response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);  
  56.             response.Headers.Add("Access-Control-Expose-Headers""Token,TokenExpiry");  
  57.             return response;  
  58.         }  
  59.     }  
  60. }  
The controller is decorated with our authentication filter as in the following:
  1. [APIAuthenticationFilter]  
  2. public class AuthenticateController : APIController  
So, each and every request coming through this controller will need to through this authentication filter that checks for a BasicAuthentication header and credentials. The Authentication filter sets the CurrentThread principal to the authenticated Identity.

There is a single Authenticate method / action in this controller. You can decorate it with multiple endpoints as was  explained in the fourth part of this series.
  1. [POST("login")]  
  2. [POST("authenticate")]  
  3. [POST("get/token")]  
The Authenticate method first checks for CurrentThreadPrincipal and if the user is authenticated or not, in other words the job is done by the authentication filter.

if (System.Threading.Thread.CurrentPrincipal!=null && System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)

When it finds that the user is authenticated, it generates an auth token using TokenServices and returns a user with Token and its expiry.
  1. response.Headers.Add("Token", token.AuthToken);  
  2. response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);  
  3. response.Headers.Add("Access-Control-Expose-Headers""Token,TokenExpiry" );  
  4. return response;  
In our BasicAuthenticationIdentity class, I intentionally used the userId property so that we can use this property when we try to generate a token, that we are doing in this controller's Authenticate method.
  1. var basicAuthenticationIdentity = System.Threading.Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;  
  2. if (basicAuthenticationIdentity != null)  
  3. {  
  4.    var userId = basicAuthenticationIdentity.UserId;  
  5.    return GetAuthToken(userId);  
  6. }  
Now when you run this application, you'll see the Authenticate API as well, just invoke this API with Basic Authentication and User credentials, you'll get the token with expiry, let's do this step-by-step.
  1. Run the application.

    Run the application

  2. Click on the first API link, in other words POST authenticate. You'll get the page to test the API.

    Click on first API link

  3. Press the TestAPI button in the right corner. In the test console, provide Header information with the Authorization set for Basic and the user credentials in Base64 format, like we did earlier. Click on Send.

    Base64 format

  4. Now, since we provided valid credentials, we'll get a token from the Authenticate controller, with its expiry time.

    Authenticate controller

In the database.

database

Here we get response 200, in other words our user is authenticated and logged into the system. The TokenExpiry is 900, in other words 15 minutes. Note that the time difference between IssuedOn and ExpiresOn is 15 minutes, this we did in the TokenServices class method GenerateToken, you can set the time as needed. The Token is 604653d8-eb21-495c-8efd-da50ef4e56d3. Now for 15 minutes we can use this token to call our other services. But before that, we should mark our other services to understand this token and respond accordingly. Keep the generated token saved so that we can use it further in calling other services that I am about to explain. So let's set up authorization on other services.

Set Up Authorization Action Filter

We already have our Authentication filter in place and we don't want to use it for authorization purposes. So we need to create a new Action Filter for authorization. This action filter will only recognize a Token coming in requests. It assumes that, requests are already authenticated using our login channel and now the user is authorized/not authorized to use other services like Products in our case, there could be n number of other services too that can use this authorization action filter. For the request to be authorized, we don't need to user credentials. Only a token (received from the Authenticate controller after successful validation) needs to be ed using the request.

Add a folder named ActionFilters to the WebAPI project. And add a class named AuthorizationRequiredAttribute.

Deriving from ActionFilterAttribute.

ActionFilters

Override the OnActionExecuting method of ActionFilterAttribute, this is the way we define an action filter in an API project.

  1. using System.Linq;  
  2. using System.Net;  
  3. using System.Net.Http;  
  4. using System.Web.Http.Controllers;  
  5. using System.Web.Http.Filters;  
  6. using BusinessServices;  
  7.   
  8. namespace WebAPI.ActionFilters {  
  9.     public class AuthorizationRequiredAttribute: ActionFilterAttribute {  
  10.         private const string Token = "Token";  
  11.   
  12.         public override void OnActionExecuting(HttpActionContext filterContext) {  
  13.             // Get API key provider  
  14.             var provider = filterContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(ITokenServices)) as ITokenServices;  
  15.   
  16.             if (filterContext.Request.Headers.Contains(Token)) {  
  17.                 var tokenValue = filterContext.Request.Headers.GetValues(Token).First();  
  18.   
  19.                 // Validate Token  
  20.                 if (provider != null && !provider.ValidateToken(tokenValue)) {  
  21.                     var responseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized) {  
  22.                         ReasonPhrase = "Invalid Request"  
  23.                     };  
  24.                     filterContext.Response = responseMessage;  
  25.                 }  
  26.             } else {  
  27.                 filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);  
  28.             }  
  29.   
  30.             base.OnActionExecuting(filterContext);  
  31.   
  32.         }  
  33.     }  
  34. }  
The overridden method checks for the “Token” attribute in the Header of every request. If the token is present, it calls the ValidateToken method from TokenServices to check if the token exists in the database. If the token is valid, our request is navigated to the actual controller and the action that we requested, else you'll get an error message saying unauthorized.

Mark Controllers with Authorization filter

We have our action filter ready. Now let's mark our controller ProductController with this attribute. Just open the Product controller class and at the top just decorate that class with this ActionFilter attribute as in the following:
  1. [AuthorizationRequired]  
  2. [RoutePrefix("v1/Products/Product")]  
  3. public class ProductController : APIController  
  4. {  
  5. }
We have marked our controller with the action filter that we created, now every request coming to the actions of this controller will need to be ed using this ActionFilter, that checks for the token in the request.

You can mark other controllers as well with the same attribute, or you can mark it at the action level as well. Assume you want certain actions to be available to all users irrespective of their authorization. Then you can just mark only those actions that require authorization and leave other actions as they are, like I explained in Step 4 of Implementing Basic Authentication.

Maintaining Session using Token


We can certainly use these tokens to maintain session as well. The tokens are issues for 900 seconds, in other words 15 minutes. Now we want that the user should be able to continue to use this token if he is using other services as well for our application. Or assume there is a case where we only want the user to finish his work on the site within 15 minutes or within his session time before he makes a new request. So when validating the token in TokenServices, what I have done is, to increase the time of the token by 900 seconds whenever a valid request comes with a valid token.
  1. /// <summary>  
  2. /// Method to validate token against expiry and existence in database.  
  3. /// </summary>  
  4. /// <param name="tokenId"></param>  
  5. /// <returns></returns>  
  6. public bool ValidateToken(string tokenId) {  
  7.     var token = _unitOfWork.TokenRepository.Get(t = > t.AuthToken == tokenId && t.ExpiresOn > DateTime.Now);  
  8.     if (token != null && !(DateTime.Now > token.ExpiresOn)) {  
  9.         token.ExpiresOn = token.ExpiresOn.AddSeconds(  
  10.         Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));  
  11.         _unitOfWork.TokenRepository.Update(token);  
  12.         _unitOfWork.Save();  
  13.         return true;  
  14.     }  
  15.     return false;  
  16. }  
In the preceding code for token validation, first we check if the requested token exists in the database and is not expired. We check expiry by comparing it with the current date and time. If it is a valid token then we just update the token into the database with a new ExpiresOn time that is adding 900 seconds.
  1. if (token != null && !(DateTime.Now > token.ExpiresOn)) {  
  2.     token.ExpiresOn = token.ExpiresOn.AddSeconds(  
  3.     Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));  
  4.     _unitOfWork.TokenRepository.Update(token);  
  5.     _unitOfWork.Save();  
  6. }  
By doing this we can allow the end user or client to maintain session and continue using our services/application with a session timeout of 15 minutes. This approach can also be leveraged in multiple ways, like making various services with various session timeouts or many such conditions could be applied when we work on actual applications using APIs.

Running the application

Our job is nearly done.

smile

We just need to run the application and test if it is working correctly. If you have saved the token you generated earlier when testing authentication then you can use it to test authorization. I am just again running the entire cycle to test the application.

Test Authentication

Repeat the tests we did earlier to get an Auth Token. Just invoke the Authenticate controller with valid credentials and Basic authorization header. I get:

authorization

And without providing an Authorization header as basic with credentials I get.

Authorization header

I just saved the token that I got in first request.

Now try to call ProductController actions.

Test Authorization

Run the application to invoke Product Controller actions. Try to invoke them without providing any Token.

Test Authorization

Invoke first service in the list,

Invoke first service

Click send.

Click send

Here we get Unauthorized, in other words because our ProductController is marked with the authorization attribute, it checks for a Token. So here our request is invalid. Now try calling this action by providing the token that we saved.

ProductController

Click on Send and we get.

Click on Send

That means we got the response and our token was valid. Now we see our Authentication and Authorization, both functionalities are working fine. You can test Sessions on your own.

Authentication and Authorization

Likewise you can test all actions. You can create other controllers and test the security and play around with sets of permutations and combinations.

Conclusion

We covered and learned a lot. In this article I tried to explain about how to build an API application with basic Authentication and Authorization. One can mould this concept to achieve the level of security needed. Like the token generation mechanism could be customized as per one's requirements. Two levels of security could be implemented where authentication and authorization is needed for every service. One can also implement authorization on actions based on roles.

security

Image credit: http://www.greencountryfordofparsons.com

I already stated that there is no specific way to do security, the more you understand the concept, the more secure you can make the system. The techniques used in this article or the design implemented in this article should be leveraged well if you use it with Secure Socket Layer (SSL), running the REST APIs on https. In my next article I'll try to explain some more beautiful implementations and concepts. Until then Happy Coding.

You can also download the complete source code with all packages from Github.

References 


Similar Articles