a blog for those who code

Monday 20 February 2017

How to implement basic authentication in ASP.Net Web API 2

In this post we will be discussing about implementing basic authentication in ASP.Net Web API 2. Security is major concern when we expose our business through services, thus security can be achieved with simple basic authentication in our services. Authentication is all about the identity of an end user, i.e. validating the identity of a user who is accessing or consuming our services.

What is Basic Authentication ?


Basic authentication is a mechanism where an end user gets authenticated with the help of plain credentials such as username and password. In this type of authentication, end user makes a request with user name and password embedded in request header and the service returns the response accordingly if the user is authenticated or not, by checking the username and password.

Implementing Basic Authentication in Web API 2


To implement Basic Authentication we have to create a class and derive that class from AuthorizationFilterAttribute (under System.Web.Http.Filters). We need to override onAuthorization method to add a custom logic. We need to check the header of the ActionContext to authorize the user as because for Basic Authentication client send the credentials using a header.



Code 


public override void OnAuthorization(HttpActionContext actionContext)
{
 var auth = actionContext.Request.Headers.Authorization;
 // If Authorization is null that means client has not sent the authorization header
 if(auth == null && auth.Parameter == null) 
 {
  // Send UnAuthorized Error
 }
 else
 {
  //In Basic Authentication client send the credentials in base64 of username:password.
    // Thus we have to decode the base64 to get the headervalue (i.e. username:password)
  var headerValue = Encoding.Default.GetString(Convert.FromBase64String(auth.Paramter));
  // Splitting the string on colon (:) to get username and password
  var userCredentials = headerValue.Split(':');
  var username = userCredentials[0];
  var password = userCredentials[1];
  // Check if username password matches, then authorized otherwise unauthorized
 }
}

Disadvantages of using Basic Authentication


Though implementing basic authentication id dead simple but it also has disadvantages like it send the user credentials in plain text. So the credentials are very prone to hack. One more disadvantage is that we have to send the Authentication header on each request thus its more work involved.


Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment