Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Call web api service with basic authentication using jquery ajax

Suggested Videos
Part 16 - Enable SSL in Visual Studio Development Server
Part 17 - ASP.NET Web API enable HTTPS
Part 18 - Implementing basic authentication in ASP.NET Web API

In this video we will discuss how to pass basic authentication credentials to the Web API service using jQuery AJAX.

Depending on the credentials provided the web api service should authenticate and return the correct results. If female username and password are used only female employees should be returned. If male username and password are used only male employees should be returned. 
asp net web api basic authentication jquery

If invalid username and password are used the service should return 401 Unauthorized message.
basic authentication web api jquery

HTML and jQuery code used in the demo. Copy and paste the following code in HtmlPage1.html in ClientApplication project.

<!DOCTYPE html>
    <meta charset="utf-8" />
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var ulEmployees = $('#ulEmployees');

            $('#btn').click(function () {
                // Get the username & password from textboxes
                var username = $('#txtUsername').val();
                var password = $('#txtPassword').val();

                    type: 'GET',
                    // Make sure to change the port number to
                    // where you have the employee service
                    // running on your local machine
                    url: 'http://localhost:35171/api/Employees',
                    dataType: 'json',
                    // Specify the authentication header
                    // btoa() method encodes a string to Base64
                    headers: {
                        'Authorization': 'Basic ' + btoa(username + ':' + password)
                    success: function (data) {
                        $.each(data, function (index, val) {
                            var fullName = val.FirstName + ' ' + val.LastName;
                            ulEmployees.append('<li>' + fullName + ' (' + val.Gender + ')</li>')
                    complete: function (jqXHR) {
                        if (jqXHR.status == '401') {
                            ulEmployees.append('<li style="color:red">'
                                + jqXHR.status + ' : ' + jqXHR.statusText + '</li>')

            $('#btnClear').click(function () {
    Username : <input type="text" id="txtUsername" />
    Password : <input type="password" id="txtPassword" />
    <br /><br />
    <input id="btn" type="button" value="Authenticate and Get Employees" />
    <input id="btnClear" type="button" value="Clear" />
    <ul id="ulEmployees"></ul>

ASP.NET Web API tutorial for beginners