Click here to Skip to main content
15,867,308 members
Articles / Web Development / HTML

RESTful Day #5: Security in Web APIs-Basic Authentication and Token based custom Authorization in Web APIs using Action Filters

Rate me:
Please Sign up or sign in to vote.
4.96/5 (168 votes)
1 Mar 2016CPOL21 min read 1.1M   44.1K   291   186
This article will explain how to make WebAPI secure using Basic Authentication and Token based authorization.

Table of Contents

Introduction

Security has always been a major concern we talk about enterprise level applications, especially when we talk about exposing our business through services. I have already explained a lot on WebAPI in my earlier articles of the series. I explained, how do we create a WebAPI, how to resolve dependencies to make it a loosely coupled design, defining custom routes, making use of attribute routing. My article will explain how we can achieve 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 we can 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 which suits best to our application.

Roadmap

Following is the roadmap I have setup to learn WebAPI step by step,

Image 1

I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can do it.

Security in WebAPI

Security in itself is very complicated and tricky topic. I’ll try to explain how we can achieve 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 if used well makes our application secure, in our case makes our WebAPI more secure.

Image 2

Authentication

Authentication is all about the identity of an 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 in our system? Credentials can be in the form of a user name and password. We’ll use Basic Authentication technique to understand how we can achieve authentication in WebAPI.

Authorization

Authorization should be considered as a second step after authentication to achieve security. Authorization means what all permissions the authenticated user has to access web resources. Is allowed to access/ perform action on that resource? This could be achieved by setting roles and permissions for an end user who is authenticated, or can be achieved through 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 i.e. HTTP. We can achieve maintaining session in Web API through token based authorization technique. An authenticated user will be allowed to access resources for a particular 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 achieved 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 gets authenticated through our service i.e. RESTful service with the help of plain credentials such as user name and password. An end user makes a request to the service for authentication with user name and password embedded in request header. Service receives the request and checks if the credentials are valid or not, and returns the response accordingly, in case of invalid credentials, service responds with 401 error code i.e. unauthorized. The actual credentials through which comparison is don may lie in 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 when it comes to implementation, it is very easy to implement, it is nearly supported by all modern browsers and has become an authentication standard in RESTful / Web APIs. It has disadvantages like sending user credentials in plain text, sending user credentials inside request header, i.e. prone to hack. One have to send credentials each time a service is called. No session is maintained and a user cannot logout once logged in through basic authentication. It is very prone to CSRF (Cross Site Request Forgery).

Token Based Authorization

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

WebAPI with Basic Authentication and Token Based Authorization

Image 3

Creating User Service

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

Image 4

We have BusinessEntities, BusinessServices, DataModel, DependencyResolver and a WebApi project as well.

We already have a User table in database, or you can create your own database with a table like User Table as shown below,

Image 5

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

UserServices

Go to BusinessServices project and add a new interface IUserService and a service named UserServices implementing that interface,

Image 6

Image 7

Just define one method named Authenticate in the interface.

C#
namespace BusinessServices
{
    public interface IUserServices
    {
        int Authenticate(string userName, string password);
    }
}

This method takes username and password as a parameter and returns particular userId if the user is authenticated successfully.

Just implement this method in UserServices.cs class, just like we created services earlier in the series,

C#
using DataModel.UnitOfWork;

namespace BusinessServices
{
    /// <summary>
    /// Offers services for user specific operations
    /// </summary>
    public class UserServices : IUserServices
    {
        private readonly UnitOfWork _unitOfWork;

        /// <summary>
        /// Public constructor.
        /// </summary>
        public UserServices(UnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// Public method to authenticate user by user name and password.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public int Authenticate(string userName, string password)
        {
            var user = _unitOfWork.UserRepository.Get(u => u.UserName == userName && u.Password == password);
            if (user != null && user.UserId > 0)
            {
                return user.UserId;
            }
            return 0;
        }
    }
}

You can clearly see that Authenticate method just checks user credentials from UserRepository and returns the values accordingly. The code is very much self-explanatory.

Resolve dependency of UserService

Just open DependencyResolver class in BusinessServices project otself and add its dependency type so that we get UserServices dependency resolved at run time,so add

C#
registerComponent.RegisterType<IUserServices, UserServices>();

line to SetUP method. Our class becomes,

C#
using System.ComponentModel.Composition;
using DataModel;
using DataModel.UnitOfWork;
using Resolver;

namespace BusinessServices
{
    [Export(typeof(IComponent))]
    public class DependencyResolver : IComponent
    {
        public void SetUp(IRegisterComponent registerComponent)
        {
            registerComponent.RegisterType<IProductServices, ProductServices>();
            registerComponent.RegisterType<IUserServices, UserServices>();
        }
    }
}

Implementing Basic Authentication

Step 1: Create 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 will be like,

C#
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class GenericAuthenticationFilter : AuthorizationFilterAttribute
{

    /// <summary>
    /// Public default Constructor
    /// </summary>
    public GenericAuthenticationFilter()
    {
    }

    private readonly bool _isActive = true;

    /// <summary>
    /// parameter isActive explicitly enables/disables this filetr.
    /// </summary>
    /// <param name="isActive"></param>
    public GenericAuthenticationFilter(bool isActive)
    {
        _isActive = isActive;
    }

    /// <summary>
    /// Checks basic authentication request
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnAuthorization(HttpActionContext filterContext)
    {
        if (!_isActive) return;
        var identity = FetchAuthHeader(filterContext);
        if (identity == null)
        {
            ChallengeAuthRequest(filterContext);
            return;
        }
        var genericPrincipal = new GenericPrincipal(identity, null);
        Thread.CurrentPrincipal = genericPrincipal;
        if (!OnAuthorizeUser(identity.Name, identity.Password, filterContext))
        {
            ChallengeAuthRequest(filterContext);
            return;
        }
        base.OnAuthorization(filterContext);
    }

    /// <summary>
    /// Virtual method.Can be overriden with the custom Authorization.
    /// </summary>
    /// <param name="user"></param>
    /// <param name="pass"></param>
    /// <param name="filterContext"></param>
    /// <returns></returns>
    protected virtual bool OnAuthorizeUser(string user, string pass, HttpActionContext filterContext)
    {
        if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pass))
            return false;
        return true;
    }

    /// <summary>
    /// Checks for autrhorization header in the request and parses it, creates user credentials and returns as BasicAuthenticationIdentity
    /// </summary>
    /// <param name="filterContext"></param>
    protected virtual BasicAuthenticationIdentity FetchAuthHeader(HttpActionContext filterContext)
    {
        string authHeaderValue = null;
        var authRequest = filterContext.Request.Headers.Authorization;
        if (authRequest != null && !String.IsNullOrEmpty(authRequest.Scheme) && authRequest.Scheme == "Basic")
            authHeaderValue = authRequest.Parameter;
        if (string.IsNullOrEmpty(authHeaderValue))
            return null;
        authHeaderValue = Encoding.Default.GetString(Convert.FromBase64String(authHeaderValue));
        var credentials = authHeaderValue.Split(':');
        return credentials.Length < 2 ? null : new BasicAuthenticationIdentity(credentials[0], credentials[1]);
    }


    /// <summary>
    /// Send the Authentication Challenge request
    /// </summary>
    /// <param name="filterContext"></param>
    private static void ChallengeAuthRequest(HttpActionContext filterContext)
    {
        var dnsHost = filterContext.Request.RequestUri.DnsSafeHost;
        filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
        filterContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", dnsHost));
    }
}

Since this is an AuthorizationFilter derived class, we need to override its methods to add our custom logic. Here "OnAuthorization" method is overridden to add a custom logic. Whenever we get ActionContext on OnAuthorization, we’ll check for its header, since we are pushing our service to follow BasicAuthentication, the request headers should contain this information. I have used FetchAuthHeader to check the scheme, if it comes to be "Basic" and thereafter store the credentials i.e. user name and password in a form of an object of class BasicAuthenticationIdentity, therefore creating an identity out of valid credentials.

C#
protected virtual BasicAuthenticationIdentity FetchAuthHeader(HttpActionContext filterContext)
{
    string authHeaderValue = null;
    var authRequest = filterContext.Request.Headers.Authorization;
    if (authRequest != null && !String.IsNullOrEmpty(authRequest.Scheme) && authRequest.Scheme == "Basic")
        authHeaderValue = authRequest.Parameter;
    if (string.IsNullOrEmpty(authHeaderValue))
        return null;
    authHeaderValue = Encoding.Default.GetString(Convert.FromBase64String(authHeaderValue));
    var credentials = authHeaderValue.Split(':');
    return credentials.Length < 2 ? null : new BasicAuthenticationIdentity(credentials[0], credentials[1]);
}

I am expecting values to be encrypted using Base64 string; You can use your own encryption mechanism as well.

Later on in OnAuthorization method we create a genericPrincipal with the created identity and assign it to current Thread principal,

C#
var genericPrincipal = new GenericPrincipal(identity, null);
Thread.CurrentPrincipal = genericPrincipal;
if (!OnAuthorizeUser(identity.Name, identity.Password, filterContext))
{
    ChallengeAuthRequest(filterContext);
    return;
}
base.OnAuthorization(filterContext);

Once done, a challenge to that request is added, where we add response and tell the Basic realm,

C#
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 generic authentication principal to the current thread principal.

Since we know the drawback that in basic authentication credentials are passed in a plain text, so it would be good if our service uses SSL for communication or message passing.

We have an overridden constructor as well that allows to stop the default behavior of the filter by just passing in a parameter i.e. true or false.

C#
public GenericAuthenticationFilter(bool isActive)
      {
          _isActive = isActive;
      }

We can use OnAuthorizeUser for custom authorization purposes.

Step 2: Create Basic Authentication Identity

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

This class contains three properties i.e. UserName, Password and UserId. I purposely added UserId because we’ll need that in future. So our class will be like,

C#
using System.Security.Principal;

namespace WebApi.Filters
{
    /// <summary>
    /// Basic Authentication identity
    /// </summary>
    public class BasicAuthenticationIdentity : GenericIdentity
    {
        /// <summary>
        /// Get/Set for password
        /// </summary>
        public string Password { get; set; }
        /// <summary>
        /// Get/Set for UserName
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// Get/Set for UserId
        /// </summary>
        public int UserId { get; set; }

        /// <summary>
        /// Basic Authentication Identity Constructor
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public BasicAuthenticationIdentity(string userName, string password)
            : base(userName, "Basic")
        {
            Password = password;
            UserName = userName;
        }
    }
}

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 first step. This class overrider OnAuthorizeUser method to add custom logic for authenticating a request it makes use of UserService that we created earlier to check the user,

C#
protected override bool OnAuthorizeUser(string username, string password, HttpActionContext actionContext)
        {
            var provider = actionContext.ControllerContext.Configuration
                               .DependencyResolver.GetService(typeof(IUserServices)) as IUserServices;
            if (provider != null)
            {
                var userId = provider.Authenticate(username, password);
                if (userId>0)
                {
                    var basicAuthenticationIdentity = Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
                    if (basicAuthenticationIdentity != null)
                        basicAuthenticationIdentity.UserId = userId;
                    return true;
                }
            }
            return false;
        }
Complete class
C#
using System.Threading;
using System.Web.Http.Controllers;
using BusinessServices;

namespace WebApi.Filters
{
    /// <summary>
    /// Custom Authentication Filter Extending basic Authentication
    /// </summary>
    public class ApiAuthenticationFilter : GenericAuthenticationFilter
    {
        /// <summary>
        /// Default Authentication Constructor
        /// </summary>
        public ApiAuthenticationFilter()
        {
        }

        /// <summary>
        /// AuthenticationFilter constructor with isActive parameter
        /// </summary>
        /// <param name="isActive"></param>
        public ApiAuthenticationFilter(bool isActive)
            : base(isActive)
        {
        }

        /// <summary>
        /// Protected overriden method for authorizing user
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool OnAuthorizeUser(string username, string password, HttpActionContext actionContext)
        {
            var provider = actionContext.ControllerContext.Configuration
                               .DependencyResolver.GetService(typeof(IUserServices)) as IUserServices;
            if (provider != null)
            {
                var userId = provider.Authenticate(username, password);
                if (userId>0)
                {
                    var basicAuthenticationIdentity = Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
                    if (basicAuthenticationIdentity != null)
                        basicAuthenticationIdentity.UserId = userId;
                    return true;
                }
            }
            return false;
        }
    }
}

Step 4: Basic Authentication on Controller

Since we already have our products controller,

C#
public class ProductController : ApiController
 {
     #region Private variable.

     private readonly IProductServices _productServices;

     #endregion

     #region Public Constructor

     /// <summary>
     /// Public constructor to initialize product service instance
     /// </summary>
     public ProductController(IProductServices productServices)
     {
         _productServices = productServices;
     }

     #endregion

     // GET api/product
     [GET("allproducts")]
     [GET("all")]
     public HttpResponseMessage Get()
     {
         var products = _productServices.GetAllProducts();
         var productEntities = products as List<ProductEntity> ?? products.ToList();
         if (productEntities.Any())
             return Request.CreateResponse(HttpStatusCode.OK, productEntities);
         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
     }

     // GET api/product/5
     [GET("productid/{id?}")]
     [GET("particularproduct/{id?}")]
     [GET("myproduct/{id:range(1, 3)}")]
     public HttpResponseMessage Get(int id)
     {
         var product = _productServices.GetProductById(id);
         if (product != null)
             return Request.CreateResponse(HttpStatusCode.OK, product);
         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
     }

     // POST api/product
     [POST("Create")]
     [POST("Register")]
     public int Post([FromBody] ProductEntity productEntity)
     {
         return _productServices.CreateProduct(productEntity);
     }

     // PUT api/product/5
     [PUT("Update/productid/{id}")]
     [PUT("Modify/productid/{id}")]
     public bool Put(int id, [FromBody] ProductEntity productEntity)
     {
         if (id > 0)
         {
             return _productServices.UpdateProduct(id, productEntity);
         }
         return false;
     }

     // DELETE api/product/5
     [DELETE("remove/productid/{id}")]
     [DELETE("clear/productid/{id}")]
     [PUT("delete/productid/{id}")]
     public bool Delete(int id)
     {
         if (id > 0)
             return _productServices.DeleteProduct(id);
         return false;
     }
 }

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,

C#
[ApiAuthenticationFilter]
[RoutePrefix("v1/Products/Product")]
public class ProductController : ApiController

You can also globally add this in Web API configuration file , so that filter applies to all the controllers and all the actions associated to it,

C#
GlobalConfiguration.Configuration.Filters.Add(new ApiAuthenticationFilter());

You can also apply it to Action level too by your wish to apply or not apply authentication to that action,

C#
// GET api/product
 [ApiAuthenticationFilter(true)]
 [GET("allproducts")]
 [GET("all")]
 public HttpResponseMessage Get()
 {
      …………………
 }
 // GET api/product/5
  [ApiAuthenticationFilter(false)]
 [GET("productid/{id?}")]
 [GET("particularproduct/{id?}")]
 [GET("myproduct/{id:range(1, 3)}")]
 public HttpResponseMessage Get(int id)
 {
      ……………………..
 }

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,

Image 8

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 in searchbox in online packages,

Image 9

You’ll get "A simple Test Client for ASP.NET Web API", just add it. You’ll get a help controller in Areas-> HelpPage like shown below,

Image 10

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

Append "/help" in the application url, and you’ll get the test client,

GET:

Image 11

POST:

Image 12

PUT:

Image 13

DELETE:

Image 14

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 particular service. On that page there is a button Test API in the right bottom corner, just press that button to test your service,

Image 15

Service for Get All products,

Image 16

When you click on Send request, a popup will come asking Authentication required. Just cancel that popup and let request go without credentials. You’ll get a response of Unauthorized i.e. 401,

Image 17

This means our authentication mechanism is working.

Image 18

Just to double sure it, let’s send the request with credentials now. Just add a header too with the request. Header should be like ,

Authorization : Basic YWtoaWw6YWtoaWw=

Here "YWtoaWw6YWtoaWw=" is my Base64 encoded user name and password i.e. akhil:akhil

Image 19

Click on Send and we get the response as desired,

Image 20

Image 21

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 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 does not limit to securing our endpoint with authentication only.

In this design, each time I’ll have to send user name and password with every request. Suppose I want to create such application, where authentication only occurs only once as my login is done and after successfully authenticated i.e. logging in I must be able to use other services of that application i.e. I am authorized now to use those services. Our application should be that robust that it restricts even authenticated user to use other services until he is not authorized. Yes I am talking about Token based authorization.

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

After 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 user makes 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, can be made configurable with the help of web.config file. After session is expired, user will be logged out, and will again have to use login service with credentials to get a new token. Seems exciting to me, let’s implement this :)

Implementing Token based Authorization

To overcome above mentioned scenarios, let’s start developing and giving our application a shape of thick client enterprise architecture.

Image 22

Set Database

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

Image 23

Set Business Services

Just navigate to BusinessServices and create one more Interface named ITokenServices for token based operations,

C#
using BusinessEntities;

namespace BusinessServices
{
    public interface ITokenServices
    {
        #region Interface member methods.
        /// <summary>
        ///  Function to generate unique token with expiry against the provided userId.
        ///  Also add a record in database for generated token.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        TokenEntity GenerateToken(int userId);

        /// <summary>
        /// Function to validate token againt expiry and existance in database.
        /// </summary>
        /// <param name="tokenId"></param>
        /// <returns></returns>
        bool ValidateToken(string tokenId);

        /// <summary>
        /// Method to kill the provided token id.
        /// </summary>
        /// <param name="tokenId"></param>
        bool Kill(string tokenId);

        /// <summary>
        /// Delete tokens for the specific deleted user
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        bool DeleteByUserId(int userId);
        #endregion
    }
}

We have four methods defined in this interface. Let’s create TokenServices class which implements ITokenServices and understand each method.

GenerateToken method takes userId as a parameter and generates a token, encapsulates that token in a token entity with Token expiry time and returns it to caller.

C#
public TokenEntity GenerateToken(int userId)
      {
          string token = Guid.NewGuid().ToString();
          DateTime issuedOn = DateTime.Now;
          DateTime expiredOn = DateTime.Now.AddSeconds(
                                            Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
          var tokendomain = new Token
                                {
                                    UserId = userId,
                                    AuthToken = token,
                                    IssuedOn = issuedOn,
                                    ExpiresOn = expiredOn
                                };

          _unitOfWork.TokenRepository.Insert(tokendomain);
          _unitOfWork.Save();
          var tokenModel = new TokenEntity()
                               {
                                   UserId = userId,
                                   IssuedOn = issuedOn,
                                   ExpiresOn = expiredOn,
                                   AuthToken = token
                               };

          return tokenModel;
      }

While generating token, it names a database entry into Token table.

ValidateToken method just validates that the token associated with the request is valid or not i.e. it exists in the database within its expiry time limit.

C#
public bool ValidateToken(string tokenId)
      {
          var token = _unitOfWork.TokenRepository.Get(t => t.AuthToken == tokenId && t.ExpiresOn > DateTime.Now);
          if (token != null && !(DateTime.Now > token.ExpiresOn))
          {
              token.ExpiresOn = token.ExpiresOn.AddSeconds(
                                            Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
              _unitOfWork.TokenRepository.Update(token);
              _unitOfWork.Save();
              return true;
          }
          return false;
      }

It just takes token Id supplied in the request.

Kill Token just kills the token i.e. removes the token from database.

C#
public bool Kill(string tokenId)
      {
          _unitOfWork.TokenRepository.Delete(x => x.AuthToken == tokenId);
          _unitOfWork.Save();
          var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x => x.AuthToken == tokenId).Any();
          if (isNotDeleted) { return false; }
          return true;
      }

DeleteByUserId method deletes all token entries from the database w.r.t particular userId associated with those tokens.

C#
public bool DeleteByUserId(int userId)
{
_unitOfWork.TokenRepository.Delete(x => x.UserId == userId);
_unitOfWork.Save();

var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x => x.UserId == userId).Any();
return !isNotDeleted;
}

So with _unitOfWork and along with Constructor our class becomes,

C#
using System;
using System.Configuration;
using System.Linq;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;

namespace BusinessServices
{
public class TokenServices:ITokenServices
{
#region Private member variables.
private readonly UnitOfWork _unitOfWork;
#endregion

#region Public constructor.
/// <summary>
/// Public constructor.
/// </summary>
public TokenServices(UnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
#endregion


#region Public member methods.

/// <summary>
///  Function to generate unique token with expiry against the provided userId.
///  Also add a record in database for generated token.
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public TokenEntity GenerateToken(int userId)
{
string token = Guid.NewGuid().ToString();
DateTime issuedOn = DateTime.Now;
DateTime expiredOn = DateTime.Now.AddSeconds(
Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
var tokendomain = new Token
{
UserId = userId,
AuthToken = token,
IssuedOn = issuedOn,
ExpiresOn = expiredOn
};

_unitOfWork.TokenRepository.Insert(tokendomain);
_unitOfWork.Save();
var tokenModel = new TokenEntity()
{
UserId = userId,
IssuedOn = issuedOn,
ExpiresOn = expiredOn,
AuthToken = token
};

return tokenModel;
}

/// <summary>
/// Method to validate token against expiry and existence in database.
/// </summary>
/// <param name="tokenId"></param>
/// <returns></returns>
public bool ValidateToken(string tokenId)
{
var token = _unitOfWork.TokenRepository.Get(t => t.AuthToken == tokenId && t.ExpiresOn > DateTime.Now);
if (token != null && !(DateTime.Now > token.ExpiresOn))
{
token.ExpiresOn = token.ExpiresOn.AddSeconds(
Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
_unitOfWork.TokenRepository.Update(token);
_unitOfWork.Save();
return true;
}
return false;
}

/// <summary>
/// Method to kill the provided token id.
/// </summary>
/// <param name="tokenId">true for successful delete</param>
public bool Kill(string tokenId)
{
_unitOfWork.TokenRepository.Delete(x => x.AuthToken == tokenId);
_unitOfWork.Save();
var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x => x.AuthToken == tokenId).Any();
if (isNotDeleted) { return false; }
return true;
}

/// <summary>
/// Delete tokens for the specific deleted user
/// </summary>
/// <param name="userId"></param>
/// <returns>true for successful delete</returns>
public bool DeleteByUserId(int userId)
{
_unitOfWork.TokenRepository.Delete(x => x.UserId == userId);
_unitOfWork.Save();

var isNotDeleted = _unitOfWork.TokenRepository.GetMany(x => x.UserId == userId).Any();
return !isNotDeleted;
}

#endregion
}
}

Do not forget to resolve the dependency of this Token service in DependencyResolver class.  Add  registerComponent.RegisterType<ITokenServices, TokenServices>();  to the SetUp method of DependencyResolver class in BusinessServices project.

  [Export(typeof(IComponent))]
    public class DependencyResolver : IComponent
    {
        public void SetUp(IRegisterComponent registerComponent)
        {
            registerComponent.RegisterType<IProductServices, ProductServices>();
            registerComponent.RegisterType<IUserServices, UserServices>();
            registerComponent.RegisterType<ITokenServices, TokenServices>();

        }
    }

Do not forget to resolve the dependency of this Token service in DependencyResolver class. Add registerComponent.RegisterType<ITokenServices, TokenServices>(); to the SetUp method of DependencyResolver class in BusinessServices project.

C#
[Export(typeof(IComponent))]
  public class DependencyResolver : IComponent
  {
      public void SetUp(IRegisterComponent registerComponent)
      {
          registerComponent.RegisterType<IProductServices, ProductServices>();
          registerComponent.RegisterType<IUserServices, UserServices>();
          registerComponent.RegisterType<ITokenServices, TokenServices>();

      }
  }

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 login request and makes use of Token Service to generate token and respond client/caller with a token that persists in database with expiry details.

Add a new Controller under Controllers folder in WebAPI with a name Authenticate,

Image 24

AuthenticateController

C#
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AttributeRouting.Web.Http;
using BusinessServices;
using WebApi.Filters;

namespace WebApi.Controllers
{
    [ApiAuthenticationFilter]
    public class AuthenticateController : ApiController
    {
        #region Private variable.

        private readonly ITokenServices _tokenServices;

        #endregion

        #region Public Constructor

        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public AuthenticateController(ITokenServices tokenServices)
        {
            _tokenServices = tokenServices;
        }

        #endregion

       /// <summary>
       /// Authenticates user and returns token with expiry.
       /// </summary>
       /// <returns></returns>
        [POST("login")]
        [POST("authenticate")]
        [POST("get/token")]
        public HttpResponseMessage Authenticate()
        {
            if (System.Threading.Thread.CurrentPrincipal!=null && System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                var basicAuthenticationIdentity = System.Threading.Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
                if (basicAuthenticationIdentity != null)
                {
                    var userId = basicAuthenticationIdentity.UserId;
                    return GetAuthToken(userId);
                }
            }
           return null;
        }

        /// <summary>
        /// Returns auth token for the validated user.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private HttpResponseMessage GetAuthToken(int userId)
        {
            var token = _tokenServices.GenerateToken(userId);
            var response = Request.CreateResponse(HttpStatusCode.OK, "Authorized");
            response.Headers.Add("Token", token.AuthToken);
            response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
            response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry" );
            return response;
        }
    }
}

The controller is decorated with our authentication filter,

C#
[ApiAuthenticationFilter]
public class AuthenticateController : ApiController

So, each and every request coming through this controller will have to pass through this authentication filter, that check for BasicAuthentication header and credentials.Authentication filter sets CurrentThread principal to the authenticated Identity.

There is a single Authenticate method / action in this controller. You can decorate it with multiple endpoints like we discussed in fourth part of the series,

C#
[POST("login")]
[POST("authenticate")]
[POST("get/token")]

Authenticate method first checks for CurrentThreadPrincipal and if the user is authenticated or not i.e job done by authentication filter,

C#
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 with the help of TokenServices and returns user with Token and its expiry,

C#
response.Headers.Add("Token", token.AuthToken);
response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry" );
return response;

In our BasicAuthenticationIdentity class, I purposely used userId property so that we can make use of this property when we try to generate token, that we are doing in this controller’s Authenticate method,

C#
var basicAuthenticationIdentity = System.Threading.Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
if (basicAuthenticationIdentity != null)
{
var userId = basicAuthenticationIdentity.UserId;
return GetAuthToken(userId);
}

Now when you run this application, You’ll see Authenticate api as well, just invoke this api with Baisc Authentication and User credentials, you’ll get the token with expiry,let’s do this step by step.

  1. Run the application.

    Image 25

  2. Click on first api link i.e. POST authenticate. You’ll get the page to test the api,

    Image 26

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

    Image 27

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

    Image 28

In database,

Image 29

Here we get response 200, i.e. our user is authenticated and logged into system. TokenExpiry in 900 i.e. 15 minutes. Note that the time difference between IssuedOn and ExpiresOn is 15 minutes, this we did in TokenServices class method GenerateToken, you can set the time as per your need. 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 setup authorization on other services.

Setup Authorization Action Filter

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

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

Deriving from ActionFilterAttribute,

Image 30

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

C#
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using BusinessServices;

namespace WebApi.ActionFilters
{
public class AuthorizationRequiredAttribute : ActionFilterAttribute
{
private const string Token = "Token";

public override void OnActionExecuting(HttpActionContext filterContext)
{
//  Get API key provider
var provider = filterContext.ControllerContext.Configuration
.DependencyResolver.GetService(typeof(ITokenServices)) as ITokenServices;

if (filterContext.Request.Headers.Contains(Token))
{
var tokenValue = filterContext.Request.Headers.GetValues(Token).First();

// Validate Token
if (provider != null && !provider.ValidateToken(tokenValue))
{
var responseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Invalid Request" };
filterContext.Response = responseMessage;
}
}
else
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}

base.OnActionExecuting(filterContext);

}
}
}

The overridden method checks for "Token" attribute in the Header of every request, if token is present, it calls ValidateToken method from TokenServices to check if the token exists in the database. If token is valid, our request is navigated to the actual controller and 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 Product controller class and at the top just decorate that class with this ActionFilter attribute,

C#
[AuthorizationRequired]
[RoutePrefix("v1/Products/Product")]
public class ProductController : ApiController
{

We have marked our controller with the action filter that we created, now every request coming to the actions of this controller will have to be passed through this ActionFilter, that checks for the token in request.

You can mark other controllers as well with the same attribute, or you can do marking at action level as well. Supoose you want certain actions should be available to all users irrespective of their authorization then you can just mark only those actions which 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 i.e. 15 minutes. Now we want that user should continue to use this token if he is using other services as well for our application. Or suppose there is a case where we only want user to finish his work on the site within 15 minutes or within his session time before he makes a new request. So while validating 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,

C#
/// <summary>
/// Method to validate token against expiry and existence in database.
/// </summary>
/// <param name="tokenId"></param>
/// <returns></returns>
public bool ValidateToken(string tokenId)
{
    var token = _unitOfWork.TokenRepository.Get(t => t.AuthToken == tokenId && t.ExpiresOn > DateTime.Now);
    if (token != null && !(DateTime.Now > token.ExpiresOn))
    {
        token.ExpiresOn = token.ExpiresOn.AddSeconds(
                                      Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
        _unitOfWork.TokenRepository.Update(token);
        _unitOfWork.Save();
        return true;
    }
    return false;
}

In above 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 current date time. If it is valid token we just update the token into database with a new ExpiresOn time that is adding 900 seconds.

C#
if (token != null && !(DateTime.Now > token.ExpiresOn))
{
    token.ExpiresOn = token.ExpiresOn.AddSeconds(
                                  Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
    _unitOfWork.TokenRepository.Update(token);
    _unitOfWork.Save();

By doing this we can allow end user or client to maintain session and keep using our services/application with a session timeout of 15 minutes. This approach can also be leveraged in multiple ways, like making different services with different session timeouts or many such conditions could be applied when we work on real time application using APIs.

Running the application

Our job is almost done.

Image 31

We just need to run the application and test if it is working fine or not. If you have saved the token you generated earlier while testing authentication you can use same to test authorization. I am just again running the whole cycle to test application.

Test Authentication

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

Image 32

And without providing Authorization header as basic with credentials I get,

Image 33

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,

Image 34

Invoke first service in the list,

Image 35

Click send,

Image 36

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

Image 37

Click on Send and we get,

Image 38

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 by your own.

Image 39

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

Conclusion

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

Image 40

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

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

References

https://msdn.microsoft.com/en-us/magazine/dn781361.aspx

http://weblog.west-wind.com/posts/2013/Apr/18/A-WebAPI-Basic-Authentication-Authorization-Filter

Other Series

My other series of articles:

MVChttp://www.codeproject.com/Articles/620195/Learning-MVC-Part-Introduction-to-MVC-Architectu

OOPhttp://www.codeproject.com/Articles/771455/Diving-in-OOP-Day-Polymorphism-and-Inheritance-Ear

License

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


Written By
Architect https://codeteddy.com/
India India
Akhil Mittal is two times Microsoft MVP (Most Valuable Professional) firstly awarded in 2016 and continued in 2017 in Visual Studio and Technologies category, C# Corner MVP since 2013, Code Project MVP since 2014, a blogger, author and likes to write/read technical articles, blogs, and books. Akhil is a technical architect and loves to work on complex business problems and cutting-edge technologies. He has an experience of around 15 years in developing, designing, and architecting enterprises level applications primarily in Microsoft Technologies. He has diverse experience in working on cutting-edge technologies that include Microsoft Stack, AI, Machine Learning, and Cloud computing. Akhil is an MCP (Microsoft Certified Professional) in Web Applications and Dot Net Framework.
Visit Akhil Mittal’s personal blog CodeTeddy (CodeTeddy ) for some good and informative articles. Following are some tech certifications that Akhil cleared,
• AZ-304: Microsoft Azure Architect Design.
• AZ-303: Microsoft Azure Architect Technologies.
• AZ-900: Microsoft Azure Fundamentals.
• Microsoft MCTS (70-528) Certified Programmer.
• Microsoft MCTS (70-536) Certified Programmer.
• Microsoft MCTS (70-515) Certified Programmer.

LinkedIn: https://www.linkedin.com/in/akhilmittal/
This is a Collaborative Group

779 members

Comments and Discussions

 
AnswerRe: I am getting password prompt Pin
Akhil Mittal23-Jan-17 1:33
professionalAkhil Mittal23-Jan-17 1:33 
GeneralRe: I am getting password prompt Pin
Member 912997123-Mar-17 7:00
Member 912997123-Mar-17 7:00 
QuestionWhat About external login i.e for google,facebook Or how to use Owin middleware in membership based authentication Pin
varun k singh11-Jan-17 16:48
varun k singh11-Jan-17 16:48 
AnswerRe: What About external login i.e for google,facebook Or how to use Owin middleware in membership based authentication Pin
Akhil Mittal23-Jan-17 1:34
professionalAkhil Mittal23-Jan-17 1:34 
GeneralRe: What About external login i.e for google,facebook Or how to use Owin middleware in membership based authentication Pin
varun k singh23-Jan-17 17:37
varun k singh23-Jan-17 17:37 
QuestionAbout Logout Pin
Member 1251152528-Dec-16 1:24
Member 1251152528-Dec-16 1:24 
QuestionPassing the Token as parameter to filter instead of passing it in the Header Pin
Sormita23-Nov-16 1:39
Sormita23-Nov-16 1:39 
QuestionAbout System.Web.Http 4.0 Pin
mysun200814-Nov-16 20:49
mysun200814-Nov-16 20:49 
HI I use according to your explanation. vs2015 .Net Framework 4.5 Web API2.0.
var provider = actionContext.ControllerContext.Configuration
.DependencyResolver.GetService(typeof(IUserServices)) as IUserServices;
provider is null.
I would like to ask the difference between System.web.http v4 and System.web.http v5?
Thank you!

modified 15-Nov-16 19:50pm.

QuestionValidateToken Method Always add 15 minutes to Expires Pin
hendog989-Nov-16 10:43
hendog989-Nov-16 10:43 
AnswerRe: ValidateToken Method Always add 15 minutes to Expires Pin
Akhil Mittal10-Nov-16 19:09
professionalAkhil Mittal10-Nov-16 19:09 
Questionimplementing external authentication Please Help Pin
Member 1275668828-Sep-16 8:31
Member 1275668828-Sep-16 8:31 
QuestionGood Work Pin
Asolvent18-Sep-16 17:55
Asolvent18-Sep-16 17:55 
Questionlock account when login with wrong password several times. Pin
an huy15-Sep-16 6:03
an huy15-Sep-16 6:03 
QuestionGreat article! - Question about Token Pin
barodesign22-Aug-16 20:54
barodesign22-Aug-16 20:54 
QuestionCreate UI Pin
Member 13328934-Aug-16 16:31
Member 13328934-Aug-16 16:31 
QuestionGood article Pin
iamalik26-Jul-16 7:58
professionaliamalik26-Jul-16 7:58 
GeneralMy vote of 5 Pin
sengson2-Jul-16 6:27
sengson2-Jul-16 6:27 
GeneralRe: My vote of 5 Pin
Akhil Mittal4-Jul-16 20:03
professionalAkhil Mittal4-Jul-16 20:03 
QuestionLogin Controller Pin
Salman aly25-May-16 23:56
Salman aly25-May-16 23:56 
QuestionCurrent Thread identity null on requests Pin
Member 1198366416-May-16 4:38
Member 1198366416-May-16 4:38 
AnswerRe: Current Thread identity null on requests Pin
Akhil Mittal16-May-16 19:25
professionalAkhil Mittal16-May-16 19:25 
AnswerRe: Current Thread identity null on requests - Fix Pin
SoftwareGoo1-Jun-16 4:57
SoftwareGoo1-Jun-16 4:57 
QuestionStoring Token in client Pin
mr.dean13-May-16 7:51
mr.dean13-May-16 7:51 
AnswerRe: Storing Token in client Pin
Akhil Mittal16-May-16 19:24
professionalAkhil Mittal16-May-16 19:24 
GeneralRe: Storing Token in client Pin
mr.dean18-May-16 15:37
mr.dean18-May-16 15:37 

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

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