Authentication is a vital process in system programming. Authentication means verifying the user who is accessing the system. Today, we are using modern devices that have different types of apps or software and sometimes, we directly access the website from the browser. To access this application, we probably need to pass our credentials and these systems verify it. If you are a valid user, then it will allow accessing the system otherwise not.

We have available different types of authentication in .NET programming like Windows Authentication, Forms Authentication, Claim Based Authentication, Token Based Authentication etc. Today, we will discuss Token Based Authentication in detail.

What is Token Based Authentication?

Token Based Authentication is not very different from other authentication mechanisms but yes, it is more secure, more reliable, and makes your system loosely coupled. It will be a better choice to create REST APIs using token-based authentication if your API has reached a broad range of devices, like mobiles, tablets, and traditional desktops.

In token based authentication, you pass your credentials [user name and password], which go to the authentication server. The server verifies your credentials and if it is a valid user, then it will return a signed token to the client system, which has an expiration time. The client can store this token for locally using any mechanism like local storage, session storage etc. and if the client makes any other call to the server for data, then it does not need to pass its credentials every time. The client can directly pass the token to the server, which will be validated by the server and if the token is valid, then you will able to access your data.

How to implement

In this demonstration, we will use Web API as a service and Angular JS as a client. So, let me create dummy database “Test” and two tables “Users” and “Employee” respectively. Users table will store the user related information like name, username, and password. Employee table is basically for dummy data. You can use the following SQL script to generate this database and tables.

CREATE DATABASE TEST  
GO    

USE TEST  
GO    

CREATE TABLE Users(Id INT IDENTITY(1,1) PRIMARY KEY, Name varchar(255) NOT NULL, UserName varchar(50), Password varchar(50))  
INSERT INTO [TEST].[dbo].[Users](Name, UserName, Password) VALUES('Mukesh Kumar', 'Mukesh', AAAAAA');  
  

CREATE TABLE Employees(Id INT IDENTITY(1,1) PRIMARY KEY, Name varchar(255) NOT NULL, Address varchar(500))  
INSERT INTO Employees (Name, Address) VALUES('Mukesh Kumar', 'New Delhi')  
INSERT INTO Employees (Name, Address) VALUES('John Right', 'England')  
INSERT INTO Employees (Name, Address) VALUES('Chris Roy', 'France')  
INSERT INTO Employees (Name, Address) VALUES('Anand Mahajan', 'Canada')  
INSERT INTO Employees (Name, Address) VALUES('Prince Singh', 'India')  

Move to the next part and create a service that will implement token-based authentication. So, we're going to create a Web API project and for the client application, we will use AngularJS from where we will pass user credentials.

To create Web API project, first, open Visual Studio 2015 and go to File >> New >> Project. It will open New Project window. Select "Web" from Installed Template and then from the right pane, choose “ASP.NET Web Application”. Provide the name like “EmployeeService” and click OK.

The next window will provide you options to choose web application template. Here, you need to choose Web API with No Authentication and click OK. Therefore, your application is ready to run.

Before moving on, to implement token-based authentication, we have to add fthe ollowing packages as a references from NuGet Package Manager. So, just right click on references in solution and select Manage NuGet Packages. It will open NuGet Package Manager Windows; you can search these packages one by one from search box in Browse tab. Once these packages are able to find out in NuGet click to install; After Installation, these packages will be available in references.

  1. Microsoft.Owin
  2. Microsoft.Owin.Host.SystemWeb
  3. Microsoft.Owin.Security.OAuth
  4. Microsoft.Owin.Security
  5. Microsoft.AspNet.Identity.Owin

In this demonstration, we will not use Global.asax file. So, first, delete the Global.asax from solution and add new class “Startup.cs” at the same location of Global.asax file and add following code.

using EmployeeService.Provider;  
using Microsoft.Owin;  
using Microsoft.Owin.Security.OAuth;  
using Owin;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Http;  
  
[assembly: OwinStartup(typeof(EmployeeService.Startup))]  
namespace EmployeeService  
{  
    public class Startup  
    {  
        public void ConfigureAuth(IAppBuilder app)  
        {  
  
            var OAuthOptions = new OAuthAuthorizationServerOptions  
            {  
                AllowInsecureHttp = true,  
                TokenEndpointPath = new PathString("/token"),  
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),  
                Provider = new SimpleAuthorizationServerProvider()  
            };  
  
            app.UseOAuthBearerTokens(OAuthOptions);  
            app.UseOAuthAuthorizationServer(OAuthOptions);  
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());  
  
            HttpConfiguration config = new HttpConfiguration();  
            WebApiConfig.Register(config);  
        }  
  
        public void Configuration(IAppBuilder app)  
        {  
            ConfigureAuth(app);  
            GlobalConfiguration.Configure(WebApiConfig.Register);  
        }  
    }  
}   

In the above code, you can see, we are using OWIN [Open Web Interface for .Net] that is an interface between your web server and web application. So, it works as a middleware in applications, which process your incoming request and validate it. Here we are using SimpleAuthorizationServerProvider, which is nothing but a class which validate user based on their credentials. You can find this class code at the last.

Now it’s time to create a model where we can perform database operations like fetching the user information based on credentials and employee data. We can use different ways here to get data like Repository pattern with Unit of work or Dapper. But we want to make this example simple and keep the main focus on Token Based Authentication only. So, right click on solution and Click to add and then New Item and choose Ado.Net Entity Model.

Employee Model

Next window will provide you several options to connect your code with database. Here, we are selecting the first one, "EF Designer from database". It will create POCO classes for database's tables.

Entity Data Model?

In the next window, you need to choose New Connection and it provides all the details to access your database. Once you will be provided all details, just click on Test Connection to check if everything is correct and move to Next.

Sql connection

Entity Data Model

Once your connection is created with database, you will find all your database components like tables, views and SPs. So, here you just need to select only Tables and click to finish.

Entity Data Model

Once you click to finish, it will generate all database components as model in EmployeeModel.edmx file like  the following image.

Data Model

Now it’s time to create a new controller to get employee data; so, you will need to add new controller as EmployeeController and add following code.

using System.Collections.Generic;  
using System.Linq;  
using System.Web.Http;  
  
namespace EmployeeService.Controllers  
{  
    public class EmployeeController : ApiController  
    {  
        [HttpGet]  
        [Authorize]  
        public List<Employee> GetEmployees()  
        {  
            using (var db = new TESTEntities())  
            {  
                var employees = db.Employees.ToList();  
                return employees;  
            }  
        }  
    }  
}  

As we discussed above, to validate user, we are using "SimpleAuthorizationServerProvider" class which inherits from OAuthAuthorizationServerProver. Here we are overriding two methods. First one is ValidateClientAuthentication, which will validate the request. And second one is  GrantResourceOwnerCredentials, which will grant to access application based on your credentials. So, basically in this method, we are validating to user. So, it validates every request and verifies your credentials and returns the token.

using Microsoft.Owin.Security;  
using Microsoft.Owin.Security.OAuth;  
using System.Collections.Generic;  
using System.Linq;  
using System.Security.Claims;  
using System.Threading.Tasks;  
using System.Web.Http.Cors;  
  
namespace EmployeeService.Provider  
{  
    [EnableCors(origins: "*", headers: "*", methods: "*")]  
    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider  
    {  
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)  
        {  
            context.Validated(); //   
        }  
  
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)  
        {  
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);  
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });  
  
            using (var db = new TESTEntities())  
            {  
                if (db != null)  
                {  
                    var empl = db.Employees.ToList();  
                    var user = db.Users.ToList();  
                    if (user != null)  
                    {  
                        if (!string.IsNullOrEmpty(user.Where(u => u.UserName == context.UserName && u.Password == context.Password).FirstOrDefault().Name))  
                        {  
                            identity.AddClaim(new Claim("Age", "16"));  
  
                            var props = new AuthenticationProperties(new Dictionary<string, string>  
                            {  
                                {  
                                    "userdisplayname", context.UserName  
                                },  
                                {  
                                     "role", "admin"  
                                }  
                             });  
  
                            var ticket = new AuthenticationTicket(identity, props);  
                            context.Validated(ticket);  
                        }  
                        else  
                        {  
                            context.SetError("invalid_grant", "Provided username and password is incorrect");  
                            context.Rejected();  
                        }  
                    }  
                }  
                else  
                {  
                    context.SetError("invalid_grant", "Provided username and password is incorrect");  
                    context.Rejected();  
                }  
                return;  
            }  
        }  
    }  
}  

At the end, you just need to Enable CORS in WebAPIConfig file.

using Newtonsoft.Json.Serialization;  
using System.Linq;  
using System.Net.Http.Formatting;  
using System.Web.Http;  
using System.Web.Http.Cors;  
  
namespace EmployeeService  
{  
    public class WebApiConfig  
    {  
        public static void Register(HttpConfiguration config)  
        {  
            // Web API configuration and services  
  
            EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");  
            config.EnableCors(cors);  
  
            // Web API routes  
            config.MapHttpAttributeRoutes();  
  
            config.Routes.MapHttpRoute(  
                name: "DefaultApi",  
                routeTemplate: "api/{controller}/{id}",  
                defaults: new { id = RouteParameter.Optional }  
            );  
  
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();  
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();  
        }  
    }  
}   

 

So, everything is setup and looks good. Let's move to test our service. To test this open PostMan Chrome Extension and choose GET method and provide the API URL and click to Send. You can see with below image that your request has been denied by the server.

Postman-Token-Based-Authentication

Now, it’s time to validate user first and get the token. And this token will be passed with next call in the header. So, select the method as POST and pass TOKEN URL as following image shows and provide your credentials. For me, username ="Mukesh" and password="*******". Don't forget to mention grant_type as password. If everything will be set up, click to send button. 

Once server validates your credentials it will correct then it will return an access_token with expiry time as following.

Postman-Token-Based-Authentication

Now you need to call same API call as we have called earlier but this time you will need to pass your token in Headers using "Authorization" key. Token should be passed followed by "bearer yourtoken". Now you can see that we are able to get the employee data. It is because we are a valid user.

Postman-Token-Based-Authentication

Conclusion

So, we have seen how to implement Token Based Authentication in Web API and in the next part we will see how to use this token in angular js applications.

I hope this post helps you. Please put your feedback using comments which will help me improve for the next post. If you have any doubts, please ask your doubts or query in the comments section.