Authentication is the process of identifying the users based on their credentials, such as username and password. This restricts unauthorized people getting access to data or applications. There are 3 common ways of ensuring authentication. The basic method is to validate the username and password. Next method is to use smart cards and the final method is to use biometric details of the user.

From this post, we are going to talk about username and password authentication using a web API. In here we are using AuthorizationFilterAttribute class which is readily available from the System.Web.Http.Filters package to implement the authentication.

Why we use Authorization Filter class?

Authorization filters are the easiest way of handling the requests from the user and identifies whether the user has access to the application. Otherwise, UnauthorizedAccess exception will be thrown from the class. For the authorization, we will create our own class inheriting the features of the AuthorizationFilterAttribute class and overrides the OnAuthorization method by passing an action parameter. It is the method used to provide the request and response to the data we are passing.

namespace Authentication
class AuthenticationClass : AuthorizationFilterAttribute  
{  
       public override void OnAuthorization(HttpActionContext httpActionContext)  
       {  
           base.OnAuthorization(httpActionContext);  
       }  
}

The main purpose of using an HTTPAction object is to check whether the header, we are passing is null or not. For any invalid header, OnAuthorization returns unauthorized access which is the 401 error code. Thereby no unauthorized third party can access the information. Hence, it is important to check the header before proceeding to the next section of the code. Now let’s override the OnAuthorization method with our customizations.

public override void OnAuthorization(HttpActionContext httpActionContext)  {       
           if (httpActionContext.Request.Headers.Authorization != null)  {  
                     // code
            }
            else {  
              httpActionContext.unauthorizedResponse = 
           httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
            }
}

Prepare the Data

Next, we have to get the user credentials and check it against the values from the database. For this example, I’ll be using 2 dummy values to illustrate the concept. Hence, this method will return true as a result of authorized login and return false for any unauthorized credentials.

public static bool isAuthorized(string username, string password)  { 
           if( username == "admin" && password == "admin123"){
                return true;
            }
           else{
               return false;
           }  
}

So far we have overridden the OnAuthorization() method and created a new method to check the validity of the credentials. Now it’s time to implement the OnAuthorization() method combining all the components we created thus far. First, we need to create a token to store the headers of the request. For that, we use the headers property available in the HttpActionContext.

var accessToken = httpActionContext.Request.Headers.Authorization.Parameter;

Decode the credentials

As a security measure, AuthorizationFilterAttribute class encodes our credentials into the base64 encoding scheme. To get the original values we need to decode those back using UTF8 encoding scheme. For this conversion, we are going to use the default method available in the System.Text library called FromBase64String.

var decodedaccessToken = System.Text.Encoding.UTF8.GetString(  
                                 Convert.FromBase64String (accessToken)); 

After the decoding, we will obtain the username and password separated by a colon. To separate out them into 2 parts, we need to use the split function available for the strings.

 var credentials = decodedaccessToken.Split(':');  
string user = credentials[0]; // assigning values to each variable
string passwrd = credentials[1];

Check if Credential is valid

To proceed further, we need to check the validity of the credentials. For that, we will pass the variables “user” and “password” to the method that we created to check the authorization. On the return of “true” function will proceeds and for “false”, unauthorized access code is returned.

  if (isAuthorized (user, passwrd)){
        Thread.CurrentPrincipal = 
             new GenericPrincipal(new GenericIdentity(user), null);  
  }  
  else  
  {  
      httpActionContext. unauthorizedResponse = 
             httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
  } 

If the isAuthorized() returns true, a new instance of GenericPrincipal() is created and the current state of the user is assigned to it. Generic Principal takes two parameters, user identity and an array of roles names that the particular user belongs to. In here we will set that array to null and user identity as the username of the user. By now we have created the complete code to authorize the user.

Now it’s the time to create a small API, to call the function we created. For that we need to create a controller class from the namespace we used earlier “Authentification” and this class will inherit features from the ApiController class.

namespace Authentication.Controllers  
{  
    public class BasicController : ApiController  
    {  
         // GET api/value/id
         public string GetID(int id)
         {
            return id.ToString();
         } 
    }  
}  

Finally, if you are using HTTP client like Postman to check this, it is important to set the Type as “Basic Auth”.

 

Related articles

JSON Serialization and Deserialization in C#

Introduction to Stack in C#

How to Use Throw Expressions in C# 7.0

Last modified: February 22, 2019

Comments

Write a Reply or Comment

Your email address will not be published.