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.

Advertisement

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.