ASP.NET Web API Authorization By Basic Auth/OAuth2.0/JWT

In this article, we are going to learn various authorization techniques of Web API. Mainly, we will discuss three major techniques - Basic Authentication, OAuth 2.1, and JSON Web Token(JWT).

In today's article, we will learn how a basic Web API authentication works and which methods are used to access the Web API.
Later on, in the next article, we will demonstrate the OAuth2.0 and JSON Web Token (JWT).
  1. Basic Authentication
  2. OAuth2.0
  3. JWT
Source Code is available at Api_Project.
 
First, we will use a basic method/technique (Basic Web API authentication). Then, we will learn how a Web API credential passes from POSTMAN application to Web API and how a Web API first receives the credentials, authorizes or unauthorizes, and sends a response back. As we know, in the basic Web API authentication method, we use the credential as a username and password.
 
Lets's start step by step.
 
Step 1
 
First, we will create a simple database containing a single table.
 
Step 2
 
Then, we will create a simple ASP.NET MVC Web API project.
 
Step 3
 
Create a class for authentication (BasicAuthentication.cs).
 
Step 4
 
Create an Entity Framework DataModel and connect to the database.
 
Step 5
 
After that, we need to go to our controller and create a Get method to fetch the data from the database and return back.
 
Step 6
 
Finally, we will test our Web API using POSTMAN.
 

Step 1 - Create a simple Database

Lets' create a database with the name "BasicDb" and a single table with the name "Product".
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Step 2
 
Now, let's create an ASP.NET Project. For this, open Visual Studio and select New > Api_Project.
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Select Web API Project with No Authentication.
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Step 3
 
Now, create a folder named Authentication.
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Add a new class in this folder. The class name is BasicAuthentication.
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Now, add the following Authorization code to this class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Security.Principal;  
  7. using System.Threading;  
  8. using System.Web;  
  9. using System.Web.Http.Controllers;  
  10. using System.Web.Http.Filters;  
  11.   
  12. namespace Api_Project.Authentication  
  13. {  
  14.     public class BasicAuthentication : AuthorizationFilterAttribute  
  15.     {  
  16.         public override void OnAuthorization(HttpActionContext actionContext)  
  17.         {  
  18.             try  
  19.             {  
  20.                 if (actionContext.Request.Headers.Authorization != null)  
  21.                 {  
  22.                     //Taking the parameter from the header  
  23.                     var authToken = actionContext.Request.Headers.Authorization.Parameter;  
  24.                     //decode the parameter  
  25.                     var decoAuthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));  
  26.                     //split by colon : and store in variable  
  27.                     var UserNameAndPassword = decoAuthToken.Split(':');  
  28.                     //Passing to a function for authorization  
  29.                     if (IsAuthorizedUser(UserNameAndPassword[0], UserNameAndPassword[1]))  
  30.                     {  
  31.                         // setting current principle  
  32.                         Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(UserNameAndPassword[0]), null);  
  33.                     }  
  34.                     else  
  35.                     {  
  36.                         actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
  37.                     }  
  38.                 }  
  39.                 else  
  40.                 {  
  41.                     actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
  42.                 }  
  43.             }  
  44.             catch (Exception ex)  
  45.             {  
  46.                 ex.Message.ToString();  
  47.             }  
  48.         }  
  49.         public static bool IsAuthorizedUser(string Username, string Password)  
  50.         {  
  51.             // In this method we can handle our database logic here...  
  52.             //Here we have given the hard-coded values   
  53.             return Username == "shahbaz" && Password == "abc123";  
  54.         }  
  55.     }  

Step 4
 
Now, we need to connect our Web API to the database using Entity Framework. Just create a DataContext Model.
 
Add>New>DataContext.
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Select EF Designer from the database.
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Select the database name on the next screen.
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Select the table and click "Finish".
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT 
 
Step 5
 
Create a Web API Controller now. For that, go to Add > New > Web API 2 Controller - Empty.
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT 
 
Add this code to the Controller.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using Api_Project.Models;  
  8.   
  9. namespace Api_Project.Controllers  
  10. {  
  11.     [RoutePrefix("Api/Product")]  
  12.     public class ProductController : ApiController  
  13.     {  
  14.         [Authentication.BasicAuthentication]  
  15.         [HttpGet]  
  16.         [Route("ProductDetails")]  
  17.         public List<Product_Table> GetProducts()  
  18.         {  
  19.             using (BasicDbEntities db=new BasicDbEntities())  
  20.             {  
  21.                 return db.Product_Table.ToList();  
  22.             }     
  23.         }  
  24.     }  

ProductController.cs
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Step 6
 
Now, we will test our Web API using POSTMAN. If you don't have POSTMAN, please download it.
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
Now, paste the URL and press Enter. Look at the highlighted message (401 Unauthorized) because we didn't pass the credentials. Let's pass the credential Username and password. Given below is the output. 
 
ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT
 
WowASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT!  We did it successfully. We have returned the data from the database and successfully authorized the credentials.
 
If you find anything wrong in this article or you have a query, please write in the comment section below.
 
Part 2 and Part 3 will be coming soon.ASP.NET Web API Authorization By Basic Auth/Oauth2.0/JWT