Web API - Basic Authentication

Basic Authentication

As per RFC 2617, HTTP Authentication: Basic and Digest Access Authentication, Basic Authentication is defined as client must authenticate itself with a user-ID and a password for each realm. Basic authentication is performed within the context of a "realm." The server includes the name of the realm in the WWW-Authenticate header. The user's credentials are valid within that realm. Simply to authenticate using Basic Authentication, client shoud pass credentials for each request in "Authentication" header as "Basic BASE64(ASCIIEncoding/ISO-8859-1 encoding of 'USERNAME:PASSWORD')".

Pros

  • Internet standard.
  • Supported by all major browsers.
  • Relatively simple protocol.

Cons

  • User credentials are sent in the request.
  • Credentials are sent as plaintext.
  • Credentials are sent with every request.
  • No way to log out, except by ending the browser session.
  • Vulnerable to cross-site request forgery (CSRF); requires anti-CSRF measures.


Adding Basic Authentication to Web API

To add the Basic authentication to our API, we need to override the OnAuthorization() method,which performs all the validations, in AuthorizeAttribute class. In that we need to check whether the header is present or not and if present, we need to extract the username and password and need to verify those details.

public class BasicAuthenticationAttribute : AuthorizeAttribute
{
 public override void OnAuthorization(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 decoded = ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(authenticationString));
   var credentials = decoded.Split(':');
   
   // encoded string is invalid
   if(credentials.Length<=2)
    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

   // Validate username and password  
   if (!Validator.ValidateUser(credentials[0], credentials[1]))
   {
    // returns unauthorized error  
    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
   }
  }
 }
}
Here, Validator.ValidateUser is user function to validate the user details.

Passing Basic Authentication while calling Web API

In order to add Basic authentication header to a web api request we need to encode our credentials as below

string username = "Your username";
string password = "Your password";
string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"{username}:{password}));
request.Headers.Add("Authorization", "Basic " + credentials);

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment