In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read our previous article where we discussed the basics of Authentication and Authorization in Web API. As part of this article, we are going to discuss the following pointers.
Let’s start the discussion with one of the Rest Constraint i.e. Stateless Constraint. The Stateless Constraint is one of the Rest Constraints which states that the communication between the client and server must be stateless between the requests. This means that we should not be storing the client information on the server which required to process the request. The request that is coming from the client should contain all the necessary information that is required by the server to process that request. This ensures that each request coming from the client can be treated independently by the server.
The above approach is fine and the advantage is that we can separate the client or server at any given point of time without affecting others. Here, the client can be any type of application including JavaScript or any other programming languages like Java or C#. The server does not remember the client once the request has been processed, so each and every request coming from the client is new to the server and the server needs to check the request (most of the time the HTTP header) to identify the user.
So, in order to process the request by the server, the client needs to pass its credentials with each and every request and then the server will check and match the credentials with any persistent storage (most of the time it may be a database). If the credentials are found in the persistent storage then the server will treat that HTTP request as a valid request and process it else it simply returns an unauthorized error to the client.
We can implement the Authentication and Authorization in many ways in an application. Here, in this article, I will discuss how to implement ASP.NET Web API Basic Authentication.
How Basic Authentication Work in Web API?
Please have a look at the following diagram.
If a request requires authentication and if the client didn’t send the credentials in the header (most of the time it is Authorization header), then the server will return 401 (Unauthorized). The response will also include a WWW-Authenticate header, indicating that the server supports Basic Authentication.
The client sends another request to the server, with the client credentials in the Authorization header. Generally, the client credentials are formatted as the string “name: password“, base64-encoded format.
As we attach the sensitive data (i,e. username and password) in each and every HTTP request, it should be transferred in an encoded format and the protocol should be HTTPS, then only we can protect our data over the internet.
The ASP.NET Web API Basic Authentication is performed within the context of a “realm.” The server includes the name of the realm in the WWW-Authenticate header. The user’s credentials are valid within that realm. The exact scope of a realm is defined by the server. For example, you might define several realms in order to partition resources.
Implementing Basic Authentication in ASP.NET Web API
First, create an ASP.NET Web Application with the name BasicAuthenticationWEBAPI (you can give any name) as shown in the below image.
Once you click on the OK button, it will open the “Select a template” window. From the “Select a template” window choose
Once you click on the OK Button it will take some time to create the project for us.
Creating Models
Now we need to create two models i.e. User and Employee. So Right-click on the Models folder and add a class file with the Name User and then copy and paste the below code.
User.cs
Employee.cs
UserBL.cs
EmployeeBL.cs
UserValidate.cs
Right Click on the Models folder and add a class file with the name BasicAuthenticationAttribute and then copy and paste the following code in it.
Right-click on the Controllers folder and select Add => Controller which will open the window to select the controller as shown below.
From this window select Web API 2 Controller – Empty and click on the Add button, which will open another window to give a name to your controller as shown below.
Provide the controller name as Employee and click on the Add button which will add Employee Controller within the controller folder.
Enable Web API Basic Authentication
We can enable basic authentication in many different ways by applying the BasicAuthenticationAttribute. We can apply the BasicAuthenticationAttribute attribute on a specific controller, specific action, or globally on all Web API controllers.
To enable the basic authentication across the entire Web API application, register the BasicAuthenticationAttribute as a filter using the Register() method in WebApiConfig class as shown in the below image.
We can also apply the BasicAuthenticationAttribute attribute on a specific controller which will enable the basic authentication for all the methods that are present in that controller as shown in the below image.
You can also enable the basic authentication at the action method level as shown in the below image which is only applicable to that particular action method which is decorated with the BasicAuthenticationAttribute.
Let’s first add an action method to the Employee Controller with the following business requirements. As we have two users i.e. MaleUser and FemaleUser and if the user login with the MaleUser username we want to display all the “male” employees and if the user login with the FemaleUser username we want to display all the female employees.
Along with the above business requirement, we also enable basic authentication at the action method level.
Add the following action method within the Employee controller
If you are new to the postman, I strongly recommended you read the following article, where I discussed how to download and use postman to test rest services.
https://csharptechtics.blogspot.com/2020/04/how-to-use-postman-to-test-web-api/
Let’s first make a request without passing the authorization header. Set the method type as GET, provide the request URI and click on the Send button as shown in the below image.
Here you can observe that you will get a 401 status code which is Unauthorized. Let’s make the request to use the Authorization header. The username and password need to be a colon (:) separated and must be in base64 encoded. To do so, just use the following website
https://www.base64encode.org/
Enter the username and password separated by a colon (:) in “Encode to Base64 format” textbox, and then click on the “Encode” button as shown in the below diagram which will generate the Base64 encoded value.
Once you generate the Base64 encoded string, let’s see how to use basic authentication in the header to pass the Base64 encoded value. Here we need to use the Authorization header and the value will be the Base64 encoded string followed the “BASIC” as shown below.
Authorization: BASIC TWFsZVVzZXI6MTIzNDU2
Once you click on the Send button, you can see that the status code is 200 as expected. That’s it for today. In the next article, I am going to discuss how to implement Role-Based Web API Authentication along with I will also discuss the advantages and disadvantages of using ASP.NET Web API Basic Authentication. Here, in this article, I try to explain the ASP.NET Web API Basic Authentication step by step with an example. I hope you enjoy this article.
Summary:
I hope this post will be helpful to understand the concept of ASP.NET Web API Basic Authentication
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
- Why we need Authentication in Web API?
- How Basic Authentication Work in Web API?
- How to Implement Basic Authentication in ASP.NET Web API?
- How to Enable Basic Authentication in Web API?
- Testing the ASP.NET Web API Basic Authentication using Postman
Let’s start the discussion with one of the Rest Constraint i.e. Stateless Constraint. The Stateless Constraint is one of the Rest Constraints which states that the communication between the client and server must be stateless between the requests. This means that we should not be storing the client information on the server which required to process the request. The request that is coming from the client should contain all the necessary information that is required by the server to process that request. This ensures that each request coming from the client can be treated independently by the server.
The above approach is fine and the advantage is that we can separate the client or server at any given point of time without affecting others. Here, the client can be any type of application including JavaScript or any other programming languages like Java or C#. The server does not remember the client once the request has been processed, so each and every request coming from the client is new to the server and the server needs to check the request (most of the time the HTTP header) to identify the user.
So, in order to process the request by the server, the client needs to pass its credentials with each and every request and then the server will check and match the credentials with any persistent storage (most of the time it may be a database). If the credentials are found in the persistent storage then the server will treat that HTTP request as a valid request and process it else it simply returns an unauthorized error to the client.
We can implement the Authentication and Authorization in many ways in an application. Here, in this article, I will discuss how to implement ASP.NET Web API Basic Authentication.
How Basic Authentication Work in Web API?
Please have a look at the following diagram.
If a request requires authentication and if the client didn’t send the credentials in the header (most of the time it is Authorization header), then the server will return 401 (Unauthorized). The response will also include a WWW-Authenticate header, indicating that the server supports Basic Authentication.
The client sends another request to the server, with the client credentials in the Authorization header. Generally, the client credentials are formatted as the string “name: password“, base64-encoded format.
As we attach the sensitive data (i,e. username and password) in each and every HTTP request, it should be transferred in an encoded format and the protocol should be HTTPS, then only we can protect our data over the internet.
The ASP.NET Web API Basic Authentication is performed within the context of a “realm.” The server includes the name of the realm in the WWW-Authenticate header. The user’s credentials are valid within that realm. The exact scope of a realm is defined by the server. For example, you might define several realms in order to partition resources.
Implementing Basic Authentication in ASP.NET Web API
First, create an ASP.NET Web Application with the name BasicAuthenticationWEBAPI (you can give any name) as shown in the below image.
Once you click on the OK button, it will open the “Select a template” window. From the “Select a template” window choose
- Empty template
- Web API Checkbox
- No Authentication
Once you click on the OK Button it will take some time to create the project for us.
Creating Models
Now we need to create two models i.e. User and Employee. So Right-click on the Models folder and add a class file with the Name User and then copy and paste the below code.
User.cs
namespace BasicAuthenticationWEBAPI.Models { public class User { public int ID { get; set; } public string UserName { get; set; } public string Password { get; set; } } }Similarly, right-click on the Models folder and add a class file with the Name Employee and then copy and paste the below code.
Employee.cs
namespace BasicAuthenticationWEBAPI.Models { 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 need to create two classes which will return the list of user and employees. Right-click on the Models folder and add a class file with the Name UserBL and then copy and paste the below code.
UserBL.cs
namespace BasicAuthenticationWEBAPI.Models { public class UsersBL { public List<user> GetUsers() { // In Real-time you need to get the data from any persistent storage // For Simplicity of this demo and to keep the focus on Basic Authentication // Here we are hardcoded the data List<user> userList = new List<user>(); userList.Add(new User() { ID = 101, UserName = "MaleUser", Password = "123456" }); userList.Add(new User() { ID = 101, UserName = "FemaleUser", Password = "abcdef" }); return userList; } } }Similarly, right-click on the Models folder and add a class file with the Name EmployeeBL and then copy and paste the below code.
EmployeeBL.cs
namespace BasicAuthenticationWEBAPI.Models { public class EmployeeBL { public List<employee> GetEmployees() { // In Real-time you need to get the data from any persistent storage // For Simplicity of this demo and to keep the focus on Basic Authentication // Here we hardcoded the data List<employee> empList = new List<employee>(); for (int i = 0; i < 10; i++) { if (i > 5) { empList.Add(new Employee() { ID = i, Name = "Name" + i, Dept = "IT", Salary = 1000 + i, Gender = "Male" }); } else { empList.Add(new Employee() { ID = i, Name = "Name" + i, Dept = "HR", Salary = 1000 + i, Gender = "Female" }); } } return empList; } } }Now, we need to create a class that will check whether the username and password are valid or not. Right-click on the Models folder and add a class file with the Name UserValidate and then copy and paste the following code.
UserValidate.cs
namespace BasicAuthenticationWEBAPI.Models { public class UserValidate { //This method is used to check the user credentials public static bool Login(string username, string password) { UsersBL userBL = new UsersBL(); var UserLists = userBL.GetUsers(); return UserLists.Any(user => user.UserName.Equals(username, StringComparison.OrdinalIgnoreCase) && user.Password == password); } } }Create a Basic Authentication Filter in Web API
Right Click on the Models folder and add a class file with the name BasicAuthenticationAttribute and then copy and paste the following code in it.
namespace BasicAuthenticationWEBAPI.Models { public class BasicAuthenticationAttribute : AuthorizationFilterAttribute { private const string Realm = "My Realm"; public override void OnAuthorization(HttpActionContext actionContext) { //If the Authorization header is empty or null //then return Unauthorized if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request .CreateResponse(HttpStatusCode.Unauthorized); // If the request was unauthorized, add the WWW-Authenticate header // to the response which indicates that it require basic authentication if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized) { actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", Realm)); } } else { //Get the authentication token from the request header string authenticationToken = actionContext.Request.Headers .Authorization.Parameter; //Decode the string string decodedAuthenticationToken = Encoding.UTF8.GetString( Convert.FromBase64String(authenticationToken)); //Convert the string into an string array string[] usernamePasswordArray = decodedAuthenticationToken.Split(':'); //First element of the array is the username string username = usernamePasswordArray[0]; //Second element of the array is the password string password = usernamePasswordArray[1]; //call the login method to check the username and password if (UserValidate.Login(username, password)) { var identity = new GenericIdentity(username); IPrincipal principal = new GenericPrincipal(identity,null); Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) { HttpContext.Current.User = principal; } } else { actionContext.Response = actionContext.Request .CreateResponse(HttpStatusCode.Unauthorized); } } } } }Note: Please add the following namespaces.
using System; using System.Net; using System.Net.Http; using System.Security.Principal; using System.Text; using System.Threading; using System.Web; using System.Web.Http.Controllers; using System.Web.Http.Filters;Adding WebAPI2 Empty Controller
Right-click on the Controllers folder and select Add => Controller which will open the window to select the controller as shown below.
From this window select Web API 2 Controller – Empty and click on the Add button, which will open another window to give a name to your controller as shown below.
Provide the controller name as Employee and click on the Add button which will add Employee Controller within the controller folder.
Enable Web API Basic Authentication
We can enable basic authentication in many different ways by applying the BasicAuthenticationAttribute. We can apply the BasicAuthenticationAttribute attribute on a specific controller, specific action, or globally on all Web API controllers.
To enable the basic authentication across the entire Web API application, register the BasicAuthenticationAttribute as a filter using the Register() method in WebApiConfig class as shown in the below image.
We can also apply the BasicAuthenticationAttribute attribute on a specific controller which will enable the basic authentication for all the methods that are present in that controller as shown in the below image.
You can also enable the basic authentication at the action method level as shown in the below image which is only applicable to that particular action method which is decorated with the BasicAuthenticationAttribute.
Let’s first add an action method to the Employee Controller with the following business requirements. As we have two users i.e. MaleUser and FemaleUser and if the user login with the MaleUser username we want to display all the “male” employees and if the user login with the FemaleUser username we want to display all the female employees.
Along with the above business requirement, we also enable basic authentication at the action method level.
Add the following action method within the Employee controller
namespace BasicAuthenticationWEBAPI.Controllers { public class EmployeeController : ApiController { [BasicAuthentication] public HttpResponseMessage GetEmployees() { string username = Thread.CurrentPrincipal.Identity.Name; var EmpList = new EmployeeBL().GetEmployees(); switch (username.ToLower()) { case "maleuser": return Request.CreateResponse(HttpStatusCode.OK, EmpList.Where(e => e.Gender.ToLower() == "male").ToList()); case "femaleuser": return Request.CreateResponse(HttpStatusCode.OK, EmpList.Where(e => e.Gender.ToLower() == "female").ToList()); default: return Request.CreateResponse(HttpStatusCode.BadRequest); } } } }Testing the Web API Basic Authentication using Postman
If you are new to the postman, I strongly recommended you read the following article, where I discussed how to download and use postman to test rest services.
https://csharptechtics.blogspot.com/2020/04/how-to-use-postman-to-test-web-api/
Let’s first make a request without passing the authorization header. Set the method type as GET, provide the request URI and click on the Send button as shown in the below image.
Here you can observe that you will get a 401 status code which is Unauthorized. Let’s make the request to use the Authorization header. The username and password need to be a colon (:) separated and must be in base64 encoded. To do so, just use the following website
https://www.base64encode.org/
Enter the username and password separated by a colon (:) in “Encode to Base64 format” textbox, and then click on the “Encode” button as shown in the below diagram which will generate the Base64 encoded value.
Once you generate the Base64 encoded string, let’s see how to use basic authentication in the header to pass the Base64 encoded value. Here we need to use the Authorization header and the value will be the Base64 encoded string followed the “BASIC” as shown below.
Authorization: BASIC TWFsZVVzZXI6MTIzNDU2
Once you click on the Send button, you can see that the status code is 200 as expected. That’s it for today. In the next article, I am going to discuss how to implement Role-Based Web API Authentication along with I will also discuss the advantages and disadvantages of using ASP.NET Web API Basic Authentication. Here, in this article, I try to explain the ASP.NET Web API Basic Authentication step by step with an example. I hope you enjoy this article.
Summary:
I hope this post will be helpful to understand the concept of ASP.NET Web API 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.