Authentication In Web API


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 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 which provides access to the request and response object.


  1. namespace BasicAuthentication  
  3.    public class BasicAuthenticationAttribute : AuthorizationFilterAttribute  
  4.    {  
  5.        public override void OnAuthorization(HttpActionContext actionContext)  
  6.        {  
  7.            base.OnAuthorization(actionContext);  
  8.        }  
  9.    } 

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.


  1. public override void OnAuthorization(HttpActionContext actionContext)  
  2. {  
  3.     if (actionContext.Request.Headers.Authorization != null)  
  4.     {  
  5.         var authToken = actionContext.Request.Headers  
  6.             .Authorization.Parameter;  
  8.         // decoding authToken we get decode value in 'Username:Password' format  
  9.         var decodeauthToken = System.Text.Encoding.UTF8.GetString(  
  10.             Convert.FromBase64String(authToken));  
  12.         // spliting decodeauthToken using ':'   
  13.         var arrUserNameandPassword = decodeauthToken.Split(':');  
  15.         // at 0th postion of array we get username and at 1st we get password  
  16.         if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1]))  
  17.         {  
  18.             // setting current principle  
  19.             Thread.CurrentPrincipal = new GenericPrincipal(  
  20.                    new GenericIdentity(arrUserNameandPassword[0]), null);  
  21.         }  
  22.         else  
  23.         {  
  24.             actionContext.Response = actionContext.Request  
  25.                 .CreateResponse(HttpStatusCode.Unauthorized);  
  26.         }  
  27.     }  
  28.     else  
  29.     {  
  30.         actionContext.Response = actionContext.Request  
  31.             .CreateResponse(HttpStatusCode.Unauthorized);  
  32.     }

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.


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

If the above method returns true, then we create Generic Principle and set it to currentprinciple. 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 globally, we will declare it in WebApiConfig.cs.

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

Step 2

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


  1. namespace BasicAuthentication.Controllers  
  2. {  
  4.     public class ValuesController : ApiController  
  5.     {  
  6.         [BasicAuthentication]  
  7.         public string Get()  
  8.         {  
  9.             return "WebAPI Method Called";  
  10.         }  
  11.     }  

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

Basic Authentication in Web API

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.


  1. <script type="text/javascript">  
  2.         $.ajax({  
  3.             type: 'GET',  
  4.             url: "api/values/Get",  
  5.             datatype: 'json',  
  6.             headers:  
  7.                 {  
  8.                     Authorization: 'Basic ' + btoa(username + ':' + password)  
  9.                 },  
  10.             success: function (data) {  
  11.             },  
  12.             error: function (data) {  
  13.             }  
  14.         });          
  15.  </script>
In this article, we learned how to implement Web authentication using Web API. Autherization is another common functionality in ASP.NET. In next article, learn how to Implement Authorization using Web API.