Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

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>
<html>
<head>
    <title></title>
    <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();

                $.ajax({
                    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) {
                        ulEmployees.empty();
                        $.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.empty();
                            ulEmployees.append('<li style="color:red">'
                                + jqXHR.status + ' : ' + jqXHR.statusText + '</li>')
                        }
                    }
                });
            });

            $('#btnClear').click(function () {
                ulEmployees.empty();
            });
        });
    </script>
</head>
<body>
    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>
</body>
</html>

ASP.NET Web API tutorial for beginners

6 comments:

  1. What is token based authentication in web api?

    ReplyDelete
  2. please do implement token based implementation please

    ReplyDelete
  3. Hi All,

    I would like to get help from you guys if possible, as i am facing the issue on
    Call web api service with basic authentication using jquery ajax videos as it's not working by following the same functionalities

    ReplyDelete
  4. hey brother.. post the question properly with code and i will help u .

    ReplyDelete
  5. Run well within domain.
    -----------------------
    But cross domain means from 'ClientApplication' project's HtmlPage1.html page, error is occurs in following line of jquery-1.10.2.js

    Code in jquery:
    // Do send the request
    // This may raise an exception which is actually
    // handled in jQuery.ajax (so no try/catch here)
    xhr.send( ( s.hasContent && s.data ) || null ); //Red line shows on this line. Error:Failed to load resource: Net::ERR_FAILED
    -------------------------
    I am using Visual studio Express 2015, Chrome version 76. I have also try in Firefox, Microsoft Edge & Internet explorer.
    Why is this error coming?

    ReplyDelete
    Replies
    1. I get solution after debugging Jquery code.

      I have added following lines of code in webApiConfig.cs (as per Kudevenkat's previous video tutorials) & now, it is working. Thanks.

      EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*"); //enable Cors globally for application
      config.EnableCors(cors);

      Delete

It would be great if you can help share these free resources