Basic Authentication In WebAPI

Introduction

Nowadays, WebAPI is a trending technology. As we are exposing our WebAPI to the outside world, we should maintain security in WebAPI. It means a valid user can only access WebAPI, or else it will throw an unauthorization error. In this blog, we will discuss how we can implement basic authentication in WebAPI.

Using Code

In order to implement basic authentication, the steps are listed below.
 
Step 1 
 
Method to validate a user

Add a class called ApiSecurity and add a method called ValidateUser(string username, string password), which takes two parameters - username and password. It checks the username and password with the database value, if it succeeds it returns boolean value as true, else false.
  1. public static bool VaidateUser(string username, string password)  
  2. {  
  3.     // Check if it is valid credential  
  4.     if(true)//CheckUserInDB(username, password))  
  5.     {  
  6.         return true;  
  7.     }
  8.    else
  9.     {  
  10.         return false;  
  11.     }              

Step 2

In the second step, add a class, which will used as Authorization filter.
The class BasicAuthenticationAttribute inherits from BasicAuthenticationAttribute abstarct class.

It contains an override method OnAuthorization(), which performs all the validations. Inside method checks whether the header is present or not: if no, it sends an unauthorized, else it goes ahead to gets the values from the header. Here, we are using 64 bit encoding format to encrypt the username/password. Once you get the value from the header, it converts to original string, which contains the username and the password. Subsequently, it calls the VaidateUser() of ApiSecurity class(discussed in Step 1) with passing the required parameters to get the Boolean result. If it returns false, it sends an unauthorized error to the user.
  1. public class BasicAuthenticationAttribute : AuthorizationFilterAttribute  
  2. {  
  3.     public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)  
  4.     {  
  5.         if (actionContext.Request.Headers.Authorization == null)  
  6.         {  
  7.             actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
  8.         }  
  9.         else  
  10.         {  
  11.             // Gets header parameters  
  12.             string authenticationString = actionContext.Request.Headers.Authorization.Parameter;  
  13.             string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));  
  14.   
  15.             // Gets username and password  
  16.             string usrename = originalString.Split(':')[0];  
  17.             string password = originalString.Split(':')[1];  
  18.   
  19.             // Validate username and password  
  20.             if (!ApiSecurity.VaidateUser(usrename, password))  
  21.             {  
  22.                 // returns unauthorized error  
  23.                 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
  24.             }  
  25.         }  
  26.   
  27.         base.OnAuthorization(actionContext);  
  28.     }  

Step 3

Our authorization filter is ready and we need to register it. You can register at global, controller or action level. Here, we have added for controller level.
  1. [BasicAuthentication]  
  2. public class BlogController : ApiController  
  3. {  
  4.     // Add your action here  

Note You can add the filter in either WebApiConfig or FilterConfig class file.
  • In WebApiConfig.cs
    config.Filters.Add(new BasicAuthenticationAttribute());

  • In FilterConfig.cs
    filters.Add(new BasicAuthenticationAttribute()); 
Step 4 
 
Send an AJAX request to call WebAPI

It's time to call WebAPI through jQuery AJAX by passing the header information. In AJAX code, we added a new attribute called headers. It contains a value as authorization, btoa() to encrypt the username and password.

The btoa() method encodes a string in base-64. This method uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string.
 
You can convert a string to base 64 encoding here.
  1. $.ajax({  
  2.     url: 'http://localhost:1312/api/Blog?type=json',  
  3.     type: "POST",  
  4.     contentType: "application/json",  
  5.     data: JSON.stringify(blogData),  
  6.     dataType: "json",  
  7.     headers: { 'Authorization' :'Basic ' + btoa(username + ':' + password) },  
  8.     success: function (result) {  
  9.         // On success, 'data' contains a list of products.  
  10.         var htmlContent = "";  
  11.   
  12.         $("#blogs > tbody > tr").remove();  
  13.   
  14.         $.each(result, function (key, item) {  
  15.             htmlContent = htmlContent + "<tr><td>" + item.Id + "</td><td>" + item.Name + "</td><td>" + item.Url + "</td></tr>";  
  16.         });  
  17.   
  18.         // Appending HTML content  
  19.         $('#blogs').append(htmlContent);  
  20.     },  
  21.     error: function (err) {  
  22.         alert(err.statusText);  
  23.     }  
  24. }); 
Conclusion

We discussed about basic authentication in WebAPI. You can use it to provide security to your WebAPI Service.

Hope it helps.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now