Consuming WEB API Service with Basic Authentication

Consuming WEB API Service with Basic Authentication

In this article, I will discuss how to Consuming WEB API Service with Basic Authentication from two different types of clients. First, we will discuss how to call from a JQuery AJAX and then we will discuss how to call the API from a C# Console application.

Please read the last article, where we discussed how to implement the Role-Based Web API Authentication with an example.

Enable CORS

As we are going to consume the API using AJAX from another domain, we need to enable CORS in our application.

It’s a two steps process

Step1: Install Microsoft.AspNet.WebApi.Cors package. Execute the following command using the NuGet Package Manager Console.

Step2: Include the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file which is inside App_Start folder

EnableCorsAttribute cors = new EnableCorsAttribute(“*”, “*”, “*”);

config.EnableCors();

The complete WebApiConfig class should looks as below.

using System.Web.Http;
using System.Web.Http.Cors;
namespace RoleBasedBasicAuthenticationWEBAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors();
        }
    }
}

If you are new to CORS, then I strongly recommended you to read the following articles, where I discussed CORS in details.

https://dotnettutorials.net/lesson/cross-origin-resource-sharing-web-api/

Modifying the Controller:

In the controller, we need to create one method called GetEmployees. Depending on the credentials provided the WEB API service should authenticate and return the correct results as follows.

If the AdminUser username and password are provided then only the male employees are returned from the service. Similarly, if SuperadminUser username and password are provided then only the female employees are returned from the service. In the same way, if bothuser username and password are provided then all the employees should be returned from the service else any other case it should return BAD Request from the service

To achieve this, let’s modify the Employee Controller as shown below.

using RoleBasedBasicAuthenticationWEBAPI.Models;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Web.Http;

namespace RoleBasedBasicAuthenticationWEBAPI.Controllers
{
    public class EmployeeController : ApiController
    {
        [BasicAuthentication]
    [EnableCorsAttribute("*", "*", "*")]
        [MyAuthorize(Roles = "Admin,Superadmin")]
        [Route("api/Employees")]
        public HttpResponseMessage GetEmployees()
        {
            //var identity = (ClaimsIdentity)User.Identity;
            //var username = identity.Name;
            //OR you can use the below code to get the login username
            string username = Thread.CurrentPrincipal.Identity.Name;

            var EmpList = new EmployeeBL().GetEmployees();
            switch (username.ToLower())
            {
                case "adminuser":
                    return Request.CreateResponse(HttpStatusCode.OK,
                        EmpList.Where(e => e.Gender.ToLower() == "male").ToList());
                case "superadminuser":
                    return Request.CreateResponse(HttpStatusCode.OK,
                        EmpList.Where(e => e.Gender.ToLower() == "female").ToList());
                case "bothuser":
                    return Request.CreateResponse(HttpStatusCode.OK,EmpList);
                default:
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
    }
}

We saw in the last article, how to consume the API’s using the Postman as a client. But it is also necessary to know how to consume the APIs from different types of client.

Consuming WEB API using JQuery AJAX:

Create one empty web application and then add one HTML page with the name AJAXClient to your application. Once you add the HTML Page then copy and paste the following code.

Note: You need to be installed JQuery packages into your projects.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <!--First Installed Jquery into your application-->
    <script src="Scripts/jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var ulEmployees = $('#ulEmployees');

            $('#btnGetData').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 service
                    // running on your local machine
                    url: 'http://localhost:63228/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 EmployeeDetails = 'Name = '+ val.Name + ' Gender = ' + val.Gender + ' Dept = ' + val.Dept + ' Salary = ' + val.Salary;
                            ulEmployees.append('<li>' + EmployeeDetails + '</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="btnGetData" type="button" value="Get Employees" />
    <input id="btnClear" type="button" value="Clear" />
    <ul id="ulEmployees"></ul>
</body>
</html>

First, run the service application and then the client application.

Now go to the client application and navigate to the URL /AJAXClient.html

Provide the valid username and password and click on the GetEmployees button and you should see the data as expected.

Consuming WEB API Service with Basic Authentication

Now provide wrong username and password and see the results as 401 unauthorized as expected.

Consuming WEB API Service with Basic Authentication

Consuming WEB API using C# Client:

Create a console application and then copy and paste the following code.

Note: You need to Install Newtonsoft.Json Package into your application

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

namespace ClientApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpClientHandler handler = new HttpClientHandler();
            HttpClient client = new HttpClient(handler);
            
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", 
                        Convert.ToBase64String(Encoding.Default.GetBytes("AdminUser:123456")));

            //Need to change the PORT number where your WEB API service is running
            var result = client.GetAsync(new Uri("http://localhost:63228/api/Employees")).Result;
            
            if (result.IsSuccessStatusCode)
            {
                Console.WriteLine("Done" + result.StatusCode);
                var JsonContent = result.Content.ReadAsStringAsync().Result;

                List<Employee> empList = JsonConvert.DeserializeObject<List<Employee>>(JsonContent);
                foreach(var emp in empList)
                {
                    Console.WriteLine("Name = " + emp.Name + " Gender = " + emp.Gender + " Dept = " + emp.Dept + " Salary = " + emp.Salary);
                }
            }
            else
                Console.WriteLine("Error" + result.StatusCode);
            Console.ReadLine();
        }
    }

    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Dept { get; set; }
        public int Salary { get; set; }
    }
}

Now we have given the AdminUser username and password, so it displays only the male employees as expected as shown in the below image.

Consuming WEB API Service with Basic Authentication

In the next article, I will discuss Message Handler in WEB API with an example.

SUMMARY

In this article, I try to explain how to Consuming WEB API Service with Basic Authentication from JQuery AJAX as well as from a C# client. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *