Authentication In Web API

Introduction

Authentication is used to protect our applications and websites from unauthorized access and also, it restricts the user from accessing the information from tools like Postman and Fiddler. In this article, we will discuss basic authentication, how to call the API method using Postman, and consume the API using jQuery Ajax.

To access the web API method, we have to pass the user credentials in the request header. If we do not pass the user credentials in the request header, then the server returns a 401 (unauthorized) status code indicating the server supports Basic Authentication.

Achieve Basic Authentication

Follow the below steps for Basic Authentication.

Step 1. Let us create a class BasicAuthenticationAttribute which inherits from the AuthorizationFilterAttribute (namespace System.Web.Http.Filters;) and overrides the method OnAuthorization from the base class (AuthorizationFilterAttribute).

The OnAuthorization method has a parameter action context that provides access to the request and response object.

Code

namespace BasicAuthentication
{
    public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
        }
    }
}

Now, we use the actionContext object to check if the request header is null or not. If null, then we return 401(unauthorized) status code; if not null, then we use the request header authorization parameter for authorization and these parameters are formatted as the string “Username: Password” base64-encoded.

Code

public override void OnAuthorization(HttpActionContext actionContext)  
{  
    if (actionContext.Request.Headers.Authorization != null)  
    {  
        var authToken = actionContext.Request.Headers.Authorization.Parameter;  
  
        // Decoding authToken we get decode value in 'Username:Password' format  
        var decodeauthToken = System.Text.Encoding.UTF8.GetString(  
            Convert.FromBase64String(authToken));  
  
        // Splitting decodeauthToken using ':'  
        var arrUserNameandPassword = decodeauthToken.Split(':');  
  
        // At 0th position of array we get username and at 1st we get password  
        if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1]))  
        {  
            // Setting current principle  
            Thread.CurrentPrincipal = new GenericPrincipal(  
                new GenericIdentity(arrUserNameandPassword[0]), null);  
        }  
        else  
        {  
            actionContext.Response = actionContext.Request  
                .CreateResponse(HttpStatusCode.Unauthorized);  
        }  
    }  
    else  
    {  
        actionContext.Response = actionContext.Request  
            .CreateResponse(HttpStatusCode.Unauthorized);  
    }
}

Now, we need to decode the base64-encoded value and split by using ‘:’. After the split, we get the username at the 0th position and the password at the 1st position. Then, we pass the username and password to the below method to check whether a user is authorized or not.

Code

public static bool IsAuthorizedUser(string Username, string Password)
{
    // In this method we can handle our database logic here...
    return Username == "bhushan" && Password == "demo";
}

If the above method returns true, then we create a Generic Principle and set it to the current principle. The generic principle has two parameters - GenericIdentity and Roles.

If the methods return false, then we return 401(unauthorized) status code.

We can define BasicAuthenticationAttribute globally, at Controller, and at View. To define the basic authentication, we have to create a controller.

If we want to declare it globally, we will declare it in WebApiConfig.cs.

config.Filters.Add(new BasicAuthenticationAttribute());

Step 2. In this step, let us create a controller and decorate the Get method with BasicAuthentication.

Code

namespace BasicAuthentication.Controllers
{
    public class ValuesController : ApiController
    {
        [BasicAuthentication]
        public string Get()
        {
            return "WebAPI Method Called";
        }
    }
}

When we hit the URL in Postman without adding Basic Authentication in the request header, this will return the 401 Status code.

URL

When we add authorization and pass the credentials, it will allow us to access the Get method and return the status 200.

Basic Authentication in Web API

To access the above Web API method using jQuery AJAX, use the following code.

Script

<script type="text/javascript">
    $.ajax({
        type: 'GET',
        url: "api/values/Get",
        datatype: 'json',
        headers: {
            Authorization: 'Basic ' + btoa(username + ':' + password)
        },
        success: function(data) {
            // Handle success response here
        },
        error: function(data) {
            // Handle error response here
        }
    });
</script>

Summary

In this article, we learned how to implement Web authentication using Web API. Authorization is another common functionality in ASP.NET. In the next article, learn how to Implement Authorization using Web API.


Similar Articles