Header add

In this article, we will discuss how to implement Basic Authentication in ASP .NET Web API.

What is ASP.NET Web API?

ASP.NET Web API is a framework used to build HTTP services that reach a broad range of clients such as Browsers, Mobile applications, Desktop applications, IOTs, etc. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

ASP.NET Web API allows us different ways to implement security while exposing resources.

  1. Basic Authentication
  2. Token Based Authentication
  3. JWT Authentication etc.
Basic authentication a mechanism where end user authenticated through our provide service. 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. Service responds with 401 error code i.e. unauthorized when the user input invalid credentials.

Pros of Basic Authentication:
It is very easy to implement, it is nearly supported by all modern browsers and has become an authentication standard in RESTful / Web APIs.

Cons of Basic Authentication:
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).

Implementation of ASP.NET Web API using basic authentication
Step-1: Open VS 2017 >> File >> New Project >> ASP .NET Web Application


Choose application as Web API
Step-2: Add the below classes inside the Models folder
                          (i)   BasicAuthenticationAttribute.cs                       
    public class BasicAuthenticationAttribute : AuthorizationFilterAttribute  
       {  
         public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)  
         {  
           if (actionContext.Request.Headers.Authorization == null)  
           {  
             actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
           }  
           else  
           {  
             // Gets header parameters   
             string authenticationString = actionContext.Request.Headers.Authorization.Parameter;  
             string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));  
             // Gets username and password   
             string username = originalString.Split(':')[0];  
             string password = originalString.Split(':')[1];  
             if (APISecurity.Validate(username, password))  
             {  
               Thread.CurrentPrincipal = new GenericPrincipal(  
                 new GenericIdentity(username), null);  
             }  
             else  
             {  
               actionContext.Response = actionContext.Request  
                 .CreateResponse(HttpStatusCode.Unauthorized);  
             }  
           }  
           base.OnAuthorization(actionContext);  
         }  
       }  
            (ii) APISecurity.cs  
    public class APISecurity  
       {  
         public static bool Validate(string username, string password)  
         {  
           if (username.Equals("CoreProgramm", StringComparison.OrdinalIgnoreCase) 
             && password == "Core@4327$")  
           {  
             return true;  
           }  
           else  
           {  
             return false;  
           }  
         }  
       }  
Code Explanation >>
>> The BasicAuthenticationAttribute is responsible to authenticate the API 
   service when the end user fetch the api. Through APISecurity class we 
   define our credentials when user fetch the service it must append the 
   valid credentials otherwise the service output is invalid.
>> The Attribute We can use in Action method or Controller.
(iii) Employee.cs  : Add the employee class that return employee information.
    namespace BasicAuthenticationWebAPI.Models  
     {  
       public class Employee  
       {  
         public int EmpNo { get; set; }  
         public string EmpName { get; set; }  
         public int Salary { get; set; }  
         public string DeptName { get; set; }  
       }  
       public class Employees : List<Employee>  
       {  
         public Employees()  
         {  
           Add(new Employee() { EmpNo = 101, EmpName = "John",   
                             Salary = 12000, DeptName = "IT" });  
           Add(new Employee() { EmpNo = 102, EmpName = "Tom",  
                             Salary = 22000, DeptName = "System" });  
           Add(new Employee() { EmpNo = 103, EmpName = "Smith",   
                              Salary = 21000, DeptName = "Sales" });  
           Add(new Employee() { EmpNo = 104, EmpName = "Lora",  
                              Salary = 32000, DeptName = "HRD" });  
           Add(new Employee() { EmpNo = 105, EmpName = "Jodie",   
                              Salary = 42000, DeptName = "HRD" });  
           Add(new Employee() { EmpNo = 106, EmpName = "Wonda",   
                              Salary = 12000, DeptName = "Admin" });  
         }  
       }  
     }  
(iv) ValuesController  : Add the attribute [BasicAuthentication], and create a method GetEmployees()
    namespace BasicAuthenticationWebAPI.Controllers  
     {  
       [BasicAuthentication]  
       public class ValuesController : ApiController  
       {  
         [Route("api/employees")]  
         public HttpResponseMessage GetEmployees()  
         {  
           Employees emp = new Employees();  
           string username = Thread.CurrentPrincipal.Identity.Name;  
           if (username == "CoreProgramm")  
           {  
             return Request.CreateResponse(HttpStatusCode.OK, emp);  
           }  
           else  
           {  
             return Request.CreateResponse(HttpStatusCode.BadRequest,  
               "Unauthorized User");  
           }  
         }  
       }  
     }  
Run the application and fetch the employees API through Postman,  You can use any other tool where restful service can be cheeked.
You can see 401 Unauthorized access is show due to we haven't declare authentication.

Now add the UserName and password what are we use APISecurity.cs and see the output.
You can see status as 200 and result print as expected.
On the above image you can see there is a Authorization Token is generated while we put username and password for authentication. Instead of validate the credentials every time we use this Basic Token and fetch the service without putting username and password again and again.

/> The Source Code is available in Github.com/CoreProgramm/









 Summary

 In this tutorial we discussed how to Secure ASP .NET Web API using Basic Authentication. If have any question related to this topic then give your feedback.

Post a Comment

Previous Post Next Post