How to consume the web api basic authentication method using JQuery ? (Part 9)


In the previous post Part 8, we show that how to test the basic authentication web api using postman.
But if we have to consume the basic authentication web api method in Jquery, then we have to add headers attribute in ajax call.

Complete sample code as given below.

@{
    ViewBag.Title = "Index";
}

<script src="~/Scripts/jquery-1.10.2.js"></script>

<script type="text/javascript">
    
    function drawTable(data) {
        for (var i = 0; i < data.length; i++) {
            drawRow(data[i]);
        }
    }
    function drawRow(rowData) {
        var row = $("<tr />")
        $("#EmpDataTable").append(row);
        row.append($("<td>" + rowData.Id + "</td>"));
        row.append($("<td>" + rowData.EmpName + "</td>"));
        row.append($("<td>" + rowData.EmpAddress + "</td>"));
    }
    
    $(document).ready(function () {
        $("#btnget").on('click', function (e) {
            var username = "Admin";
            var password = "Admin";
            e.preventDefault();
            $.ajax({
                url: "http://localhost:64410/api/Emps_API_/2",
                type: "GET",
                cache: false,
                contentType: "application/json",
                dataType: "json",
                headers: { 'Authorization': 'Basic ' + btoa(username + ':' + password) }
            }).done(function (data) {
                $('#tbdata tbody').empty();
                if (!jQuery.isArray(data)) data = [data];
                drawTable(data);
                $('#btnget').prop('disabled', true);
            }).error(function (xhr, textStatus, errorThrown) {
                alert("Err " + textStatus + "   " + errorThrown);
            });
           
        });
    });
</script>

<h2>Index</h2>
<table class="table table-bordered table-striped">
    <tr>
        <td>Click Here to Received the Employee</td>
        <td>
            <input type="button" id="btnget" value="Get" />
        </td>
    </tr>

</table>

<table class="table-bordered table-striped table table-hover" id="EmpDataTable">
    <tr>
        <th>Id</th>
        <th>Emp Name</th>
        <th>EmpAddress</th>
    </tr>

</table>

Note : in the above code headers attributes of Jquery to pass the ‘Authorization’: ‘Basic ‘ + btoa(username + ‘:’ + password), which is required to do the basic authentication process.

Here btoa is JavaScript method to convert the string to base-64 code.

How to Implement Basic Authentication in Asp.net Web API 2.0 ? (Part 8)


As the name suggest, it is the most simple and basic process of doing authentication of HTTP Request in asp.net Web API.
In this process client sends the Base64-encoded credentials to the authorize header on every HTTP request, and after verification process Web API return the expected HTTP Response

In this process, it doesn’t use Session or cookies.

Step 1: Create the BasicAuthenticationAttribute class and write code for doing validation like given below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Filters;

namespace WebApi_Sample.Security
{
    public class BasicAuthenticationAttribute: AuthorizationFilterAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.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 originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));

                // Gets username and password  
                string usrename = originalString.Split(':')[0];
                string password = originalString.Split(':')[1];

                // Validate username and password  
                if (!ValidateUser.VaidateUser(usrename, password))
                {
                    // returns unauthorized error  
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }

            base.OnAuthorization(actionContext);
        }

    }
}

Step 2: Create the ValidateUser Class and write the code for doing validation in database on basis of UserName and password

namespace WebApi_Sample.Security
{
    public class ValidateUser
    {
        public static bool VaidateUser(string username, string password)
        {
            // Check if it is valid credential  
            // Here we have just hardcoded the value 
            if (username.Equals("Admin") && password.Equals("Admin")) 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

Step 3: Use the basic BasicAuthentication Attribute on the Controller as given below

Step 4. Now lunch the Postman tool and select the basic authentication option and pass the username and password as given below image

You will the get the excepted data as output.

How to secure the Asp.net Web API 2.0 ? (Part 7)


There are so many ways to secure the Web API. But in this post we will see the Authentication process using “Message Handler”.

As we know in asp.net Web API, before execution of any controller, Httprequest go through the message Handler pipeline sequence as given below image

So if we have to implement the some custom validation logic, it will be better to write code in Message Handler.

What is the Message Handler in asp.net Web API ?

>> A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.

There will be series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain as shown in above image. This pattern is also called a delegating handler.

How to write the Custom Message Handler ?
So many time we will get the scenario to write our own logic in Message Handler to perform some specific task on that scenario we have to create Custom Message handler.

To write the Custom Message Handler we have to

1. Inherit the System.Net.Http.DelegatingHandler
2. Override SendAsync Method of HttpMessageHandler as given below

 protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
   {
      // Here will be our own login
  }

How to implement Custom Authentication process in Message Handler ?

>> From client side we can pass the some Key and Value as Authentication Token. As we know before execution of API controller it will go through the message handler pipeline so in Message handler we have to validate the given Token Value, if it is correct then further execution will happen else we will send the Forbidden request

Step 1: Create some class like APIKeyHandler in Some folder like Security

Step 2: Write the logic as given below in APIKeyHandler class

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace WebApi_Sample.Security
{
    public class APIKeyHandler : DelegatingHandler
    {
        //set a default API key 
        private const string yourApiValue = "API_Sample_Value";
        

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool isValidAPIKey = false;
            IEnumerable<string> lsHeaders;
            //Validate that the api key exists

            var checkApiKeyExists = request.Headers.TryGetValues("Sample_Key", out lsHeaders);

            if (checkApiKeyExists)
            {
                if (lsHeaders.FirstOrDefault().Equals(yourApiValue))
                {
                    isValidAPIKey = true;
                }
            }

            //If the key is not valid, return an http status code.
            if (!isValidAPIKey)
                return request.CreateResponse(HttpStatusCode.Forbidden, "Sorry you have provide wrong API key.");

            //Allow the request to process further down the pipeline
            var response = await base.SendAsync(request, cancellationToken);

            //Return the response back up the chain
            return response;
        }
    }
} 

Note: In the above code DelegatingHandler is abstract class which has overridden the method of HttpMessageHandler Class.
In the above code we are passing the yourApiValue= “API_Sample_Value” and Key =”Sample_Key”

If the given input from client side is correct then it will Allow the request to process further down the pipeline else it will terminate the request.

Step 3: Register the Custom Message Code in the Application_Startmethod of Global.asax file like this

GlobalConfiguration.Configuration.MessageHandlers.Add(new APIKeyHandler());

Step 4: Run the application and Test the Api Controller get method from PostMan Tool

How to implement the custom error handling in Web API 2.0 ? (Part 6)


This is the continuous post of previous article.There are so many approach to implement the exception in asp.net Web api but In this post we will see how to implement the custom exception handling in asp.net web api 2.0.

Step 1: Create one folder i.e. Helper in asp.net Web api project and add the class and write the code like this

using System;

namespace WebApi_Sample.CustomFilterHelper
{
    public class CatchException:Exception
    {
        public CatchException(string message)
           : base(message)
        {

        }
    }
}

Step 2: Create other class i.e ProcessExceptionFilterAttribute and add the code like this

using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;

namespace WebApi_Sample.CustomFilterHelper
{
    public class ProcessExceptionFilterAttribute : ExceptionFilterAttribute, IExceptionFilter
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            //Check the Exception Type
            if (actionExecutedContext.Exception is CatchException)
            {
                //The Response Message Set by the Action During Ececution
                var res = actionExecutedContext.Exception.Message;

                //Define the Response Message
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(res),
                    ReasonPhrase = res
                };
                //Create the Error Response
                actionExecutedContext.Response = response;
            }
        }
    }
}

Step 3: Now implement the custom exception in web api method like this

Step 4: Execute the Web Api method using Post Man, you will get the exception detail like given below

How to handle the exception in Asp.net Web API ? (Part 5)


Exception handling is the one of the good approach to find out the exact error in the application at run time.
In asp.net web API there are so many approaches to handle the exception in code like

1. Using HttpResponseException
2. Using HttpError
3. Using Exception Filters
4. Using Exception Handlers

Now we will see how to use the HttpResponseException in asp.net web API action Method

This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor.

public IHttpActionResult GetEmpDetail(int id)
        {
            tblEmp objEmp = db.tblEmps.Find(id);
            if (objEmp == null)
            {
                  throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            else
            {
                return Ok(objEmp);
            }
        }

But this above method will not give the more specific error message, so if we have to get the user friendly error message we can write the code like this

If we will run the application and test on postman, then we will get the output like this