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.
- Microsoft.Owin
- Microsoft.Owin.Host.SystemWeb
- Microsoft.Owin.Security.OAuth
- Microsoft.Owin.Security
- 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.

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.









Paramvir SinghPosted Sep 25, 2018, 7:43 AM
Please provide the link to Angularjs example as well
Paramvir SinghPosted Sep 25, 2018, 7:42 AM
It worked for me very well. Thanks for such a simple example.
Srikanth Kumar RajulapatiPosted Sep 1, 2018, 5:24 AM
Hi Mukesh, You have done a great job and its working for as described in the article. Hi Folks, Please follow these steps who ever not able to get the result 1. While entering the credentials in POST method make sure those like username : YourUserName, password: YourPassword, grant_type: password. 2. Make sure that, you should select x-www-form-urlencoded option and then click on Send button to get the token generated and later follow the final step to get the Employees result.
Gautam ParmarPosted Aug 17, 2018, 12:11 PM
Not working for me as well
Maikel FernándezPosted Jun 8, 2018, 11:36 AM
How do you add .expires, .issued, and username properties in the returned token? the other examples i see online all have these 3 properties but I don't see it here?
Ionut BoroneaPosted Jan 11, 2018, 7:46 AM
I did exactly the same as in the article but API still gives me 401 Unauthorized. What could be the issue?
Alfredo Nh42Posted Jan 9, 2018, 10:48 AM
Not working { "message": "The requested resource does not support http method 'POST'." }
Greg FrazerPosted Sep 18, 2017, 3:10 AM
{ "error": "unsupported_grant_type" }
Greg FrazerPosted Sep 18, 2017, 3:10 AM
The PostMan test gives this result
Greg FrazerPosted Sep 18, 2017, 3:09 AM
This is just not working
Greg FrazerPosted Sep 18, 2017, 3:09 AM
This is just not working