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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: