How To Create ASP.NET Web API With Token-Based Authentication

What is Web API?

 
The ASP.NET Web API is an extensible framework for building HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile, etc.
 

Why Web API?

 
To consume third party data using mobile devices, tablets, browsers Web API is very useful. Web API is easy to consume, less configuration is required as compared to consuming web services. Web API returns data in JSON as well as XML format.
 

Token Based Authentication in Web API

 
Token contains information to identify a particular user which needs to be sent to the server by the client with each and every request.
 

How Does Token Based Authentication Work in Web API?

 
Client needs to send Username and password to Authorization Server. If user credentials are correct then Authorization Server generates and returns the access token (Each token has expiry time).
 
Then client needs to include access token in Authorization header of the HTTP request to access the Web API methods.
 

Step by step method to create Token Based Authentication Web API

 
Step 1
 
Create new project in Visual Studio New Project – Web – ASP .NET Web Application – rename as TokenBasedAPI - OK
 
ASP .Net Web API
 
Step 2
 
Select Empty template and Select Web API option in checkbox list
 
Select empty template 
 
Step 3
 
Add below references using NuGet Package Manager

Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth
Microsoft.Owin.CorsNewtonsoft.json
 
Right click on references – Select Manage NuGet Packages – Browse Microsoft.Owin.Host.SystemWeb Select version 4.1.0 – Click install
Follow same procedure for other references for Newtonsoft.json select version 10.0.1
 
NewtonSoft 
 
Step 4 - Add new Class in Solution
 
Right click on project name (TokenBasedAPI) – Add – New Item – Select tab Visual C# - Select Class – rename as UserAuthentication.cs
 
 Add new Class
 
Step 5
 
Add the below code in UserAuthentication.cs file
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace TokenBasedAPI  
  7. {  
  8.     public class UserAuthentication : IDisposable  
  9.     {  
  10.         public string ValidateUser(string username, string password)  
  11.         {  
  12.             string Name = username == "akash" ? "Valid" : "InValid";  
  13.             string Pass = password == "vidhate" ? "Valid" : "InValid";  
  14.   
  15.             if (Name == "Valid" && Pass == "Valid")  
  16.                 return "true";  
  17.             else  
  18.                 return "false";  
  19.         }  
  20.         public void Dispose()  
  21.         {  
  22.             //Dispose();  
  23.         }  
  24.     }  
  25. }  
Step 6
 
Again create a new class, AuthorizationServerProvider.cs, and add the below code in that class
  1. using Microsoft.Owin.Security.OAuth;  
  2. using System.Security.Claims;  
  3. using System.Threading.Tasks;  
  4.   
  5. namespace TokenBasedAPI  
  6. {  
  7.     public class AuthorizationServerProvider : OAuthAuthorizationServerProvider  
  8.     {  
  9.         public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)  
  10.         {  
  11.             context.Validated();  
  12.         }  
  13.   
  14.         public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)  
  15.         {  
  16.             using (UserAuthentication OBJ = new UserAuthentication())  
  17.             {  
  18.                 var user = OBJ.ValidateUser(context.UserName, context.Password);  
  19.                 if (user == "false")  
  20.                 {  
  21.                     context.SetError("invalid_grant""Username or password is incorrect");  
  22.                     return;  
  23.                 }  
  24.                 var identity = new ClaimsIdentity(context.Options.AuthenticationType);  
  25.                 identity.AddClaim(new Claim(ClaimTypes.Role, "SuperAdmin"));  
  26.                 identity.AddClaim(new Claim(ClaimTypes.Name, "akash"));  
  27.                 //identity.AddClaim(new Claim("Email", user.UserEmailID));  
  28.   
  29.                 context.Validated(identity);  
  30.             }  
  31.         }  
  32.     }  
  33. }  
Step 7
 
Now add new class, OwinStartup class
 
Solution Explorer – Right click on project name (TokenBasedAPI) – Add – New Item – Select tab Visual C# - Select Class – rename as Startup.cs and add the below code in Startup.cs class
  1. using System;  
  2. using Microsoft.Owin;  
  3. using Owin;  
  4. using Microsoft.Owin.Security.OAuth;  
  5. using System.Web.Http;  
  6.   
  7. [assembly: OwinStartup(typeof(TokenBasedAPI.Startup))]  
  8.   
  9. namespace TokenBasedAPI  
  10. {  
  11.     public class Startup  
  12.     {  
  13.         public void Configuration(IAppBuilder app)  
  14.         {  
  15.             app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);  
  16.   
  17.             OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions  
  18.             {  
  19.                 AllowInsecureHttp = true,  
  20.   
  21.                 //The Path For generating the Toekn  
  22.                 TokenEndpointPath = new PathString("/token"),  
  23.   
  24.                 //Setting the Token Expired Time (24 hours)  
  25.                 AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),  
  26.   
  27.                 //AuthorizationServerProvider class will validate the user credentials  
  28.                 Provider = new AuthorizationServerProvider()  
  29.             };  
  30.   
  31.             //Token Generations  
  32.             app.UseOAuthAuthorizationServer(options);  
  33.             app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());  
  34.   
  35.             HttpConfiguration config = new HttpConfiguration();  
  36.             WebApiConfig.Register(config);  
  37.         }  
  38.     }  
  39. }  
Step 8
 
Add a new class, rename it as MyClass.cs and add the below code --  it contains distributed class architecture
  1. namespace TokenBasedAPI  
  2. {  
  3.     public class MyClass  
  4.     {  
  5.         public string Name { getset; }  
  6.         public string Role { getset; }  
  7.         public string Parameter1 { getset; }  
  8.         public string Parameter2 { getset; }  
  9.     }  
  10. }  
Step 9
 
Now add new API Controller
 
In the project(TokenBasedAPI) right click on Controllers – Add – Controller – Select Web API 2 Controller – Empty – Rename Controller as Test with postfix Controller
 
Add new API Controller
 
 Add Controller
  
Now add the below code in TestController
  1. using System.Linq;  
  2. using System.Web.Http;  
  3. using System.Security.Claims;  
  4. using System.Net.Http;  
  5. using System.Net;  
  6.   
  7. namespace TokenBasedAPI.Controllers  
  8. {  
  9.     public class TestController : ApiController  
  10.     {  
  11.         [Authorize(Roles = "SuperAdmin, Admin, User")]  
  12.         [HttpGet]  
  13.         [Route("api/test/method1")]  
  14.         public HttpResponseMessage Post(MyClass myclass)  
  15.         {  
  16.             var identity = (ClaimsIdentity)User.Identity;  
  17.             var roles = identity.Claims  
  18.                         .Where(c => c.Type == ClaimTypes.Role)  
  19.                         .Select(c => c.Value);  
  20.   
  21.             myclass.Role = roles.ToString();  
  22.             myclass.Name = identity.Name;  
  23.   
  24.             return Request.CreateResponse(HttpStatusCode.Created, myclass);  
  25.         }  
  26.     }  
  27. }  

How to access Token Based Web API using Postman?

 
We can create token by url http://localhost:PortNumber/token
 
In Postman select Request type as POST and add Request URL in my case it is http://localhost:50128//token
 
Click on body – select x-www-form-urlencoded – and add key and value as
  1. username (value : akash)
  2. password (value: vidhate)
  3. grant_type (value: password)
Click on Send – you will get the access token
 
Consume Token Based API using postamn
 

To consume Web API method

 
Select request type as POST and add request URL as http://localhost:50128/api/test/method1. Click on Headers tab Add key as Authorization and value as Bearer [Enter Token Here]
 
You have to enter authorization token preceded by Bearer
 
Now click on Body – select raw – select Text as JSON (application/json)
 
Then pass the Jason as below
  1. {  
  2.     "Parameter1""value1",  
  3.     "Parameter2""value2"  
  4. }  
Consume Web API method
 

How to consume Token based authentication API in Console Application?

 
Step 1
 
Create new Console Application – New Project – Templated – Visual C# - Console Application rename as ConsumeTokenBasedAPI
 
Create Console Application
 
Step 2
 
Add new class, rename it as Token.cs and add the below code in Token.cs
 
Add Class
  1. using System;  
  2. using Newtonsoft.Json;  
  3.   
  4. namespace ConsumeTokenBasedAPI  
  5. {  
  6.     public class Token  
  7.     {  
  8.         [JsonProperty("access_token")]  
  9.         public string AccessToken { getset; }  
  10.         public string Error { getset; }  
  11.         public string Name { getset; }  
  12.         public string Role { getset; }  
  13.         public string Parameter1 { getset; }  
  14.         public string Parameter2 { getset; }  
  15.     }  
  16. }  
Add Newtonsoft.json reference Using NuGet Package manager
 
Step 3
 
Now modify Program.cs file as below,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Net.Http;  
  4. using System.Net.Http.Headers;  
  5. using Newtonsoft.Json;  
  6.   
  7. namespace ConsumeTokenBasedAPI  
  8. {  
  9.     class Program  
  10.     {  
  11.         private static string Username = string.Empty;  
  12.         private static string Password = string.Empty;  
  13.         private static string baseAddress = "http://localhost:50128/";  
  14.         static void Main(string[] args)  
  15.         {  
  16.             Token token = null;  
  17.             Username = "akash";  
  18.             Password = "vidhate";  
  19.   
  20.             token = GetAccessToken(Username, Password);  
  21.   
  22.             if (!string.IsNullOrEmpty(token.AccessToken))  
  23.             {  
  24.                 CallAPIResource(token.AccessToken);  
  25.             }  
  26.             else  
  27.             {  
  28.                 Console.WriteLine(token.Error);  
  29.             }  
  30.             Console.ReadLine();  
  31.         }  
  32.         public static Token GetAccessToken(string username, string password)  
  33.         {  
  34.             Token token = new Token();  
  35.             HttpClientHandler handler = new HttpClientHandler();  
  36.             HttpClient client = new HttpClient(handler);  
  37.             var RequestBody = new Dictionary<stringstring>  
  38.                 {  
  39.                 {"grant_type""password"},  
  40.                 {"username", username},  
  41.                 {"password", password},  
  42.                 };  
  43.             var tokenResponse = client.PostAsync(baseAddress + "token"new FormUrlEncodedContent(RequestBody)).Result;  
  44.   
  45.             if (tokenResponse.IsSuccessStatusCode)  
  46.             {  
  47.                 var JsonContent = tokenResponse.Content.ReadAsStringAsync().Result;  
  48.                 token = JsonConvert.DeserializeObject<Token>(JsonContent);  
  49.                 token.Error = null;  
  50.             }  
  51.             else  
  52.             {  
  53.                 token.Error = "Not able to generate Access Token Invalid usrename or password";  
  54.             }  
  55.             return token;  
  56.         }  
  57.   
  58.         private static void CallAPIResource(string AccessToken)  
  59.         {  
  60.             HttpClientHandler handler = new HttpClientHandler();  
  61.             HttpClient client = new HttpClient(handler);  
  62.             client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);  
  63.   
  64.             var RequestBody = new Dictionary<stringstring>  
  65.                 {  
  66.                 {"Parameter1""value1"},  
  67.                 {"Parameter2""vakue2"},  
  68.                 };  
  69.             var APIResponse = client.PostAsync(baseAddress + "api/test/method1"new FormUrlEncodedContent(RequestBody)).Result;  
  70.   
  71.             if (APIResponse.IsSuccessStatusCode)  
  72.             {  
  73.                 var JsonContent = APIResponse.Content.ReadAsStringAsync().Result;  
  74.                 //Token Message = JsonConvert.DeserializeObject<Token>(JsonContent);  
  75.                 Console.WriteLine("APIResponse : " + JsonContent.ToString());  
  76.             }  
  77.             else  
  78.             {  
  79.                 Console.WriteLine("APIResponse, Error : " + APIResponse.StatusCode);  
  80.             }  
  81.         }  
  82.     }  
  83. }  
Step 4
 
Now debug the code --  you can see the below Output
 
Output
 

Summary

 
In this blog, you learned how to create ASP .Net Web API with Token Based Authentication And Consume ASP .NET Web API in Console Application using HTTP Client. Also Consume Web API in postman.
 
Thank you for reading.