In this article, I am going to discuss how to consume Web API Service with Basic Authentication. Please read our previous article before proceeding to this article, where we discussed how to implement the Role-Based Basic Authentication in Web API with an example. We are also going to work with our previous example. As part of this article, we are going to discuss the following pointers.
As we are going to consume the Web API Service using Jquery Ajax from another domain, we need to enable CORS in our application. Enabling CORS is 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 the Register() method of WebApiConfig class in WebApiConfig.cs file which is inside App_Start folder
https://csharptechtics.blogspot.com/2020/04/cross-origin-resource-sharing-web-api.html
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 both user 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.
Consuming Web API Service 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.
Now provide the wrong username and password and see the results as 401 unauthorized as expected.
Consuming Web API Service using C# Console Application:
Create a console application and then copy and paste the following code. You need to Install Newtonsoft.Json Package into your application
In the next article, I am going to discuss Message Handler in WEB API with an example. Here, 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.
Summary:
I hope this post will be helpful to how to consume Web API Service with Basic Authentication
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
- How to enable CORS in Web API?
- How to call Web API service from JQuery using Ajax?
- How to call Web API service from C# using a Console Application?
As we are going to consume the Web API Service using Jquery Ajax from another domain, we need to enable CORS in our application. Enabling CORS is 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 the Register() method of WebApiConfig class in WebApiConfig.cs file which is inside App_Start folder
EnableCorsAttribute cors = new EnableCorsAttribute(“*”, “*”, “*”); config.EnableCors();With the above two lines of code in place, the WebApiConfig class should look 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://csharptechtics.blogspot.com/2020/04/cross-origin-resource-sharing-web-api.html
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 both user 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); } } } }In the last article, we discussed how to consume the Web API’s using the Postman as a client. But it is also necessary to know how to consume APIs from different types of clients.
Consuming Web API Service 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.
Now provide the wrong username and password and see the results as 401 unauthorized as expected.
Consuming Web API Service using C# Console Application:
Create a console application and then copy and paste the following code. 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; } } }Here, we have given the AdminUser username and password, so it displays only the male employees as expected as shown in the below image.
In the next article, I am going to discuss Message Handler in WEB API with an example. Here, 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.
Summary:
I hope this post will be helpful to how to consume Web API Service with Basic Authentication
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.