In this Video, 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 Video where we discussed the basics of Authentication and Authorization in Web API. As part of this Video, we are going to discuss the following pointers.

- Why do we need Authentication in Web API?
- How does 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
Why do we need Authentication in Web API?
Lets 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 in time without affecting others. Here, the client can be any type of application including JavaScript or any other programming language like Java, PHP, 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 Authentication and Authorization in many ways in an application. Here, in this Video, I am going to discuss how to implement ASP.NET Web API Basic Authentication.
How does Basic Authentication Work in Web API?
Before implementing the Basic Authentication in ASP.NET Web API, let us first understand how does the basic authentication work in Web API? To understand how does basic authentication works, please have a look at the following diagram.
In Basic Authentication, if the client didnt send the credentials in the request 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 and that you can see in the above image for the first request which does not include the Authorization header.
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 and this time server validates the client and processes the request and if everything is fine, then you will get 200 OK status which you can see in the above image for the second request.
In Basic Authentication, 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 (base64-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 users 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
And finally, click on the OK button as shown below
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.cs and then copy and paste the below code into it. This is a very simple class having only three properties i.e. ID, UserName and Password.
Similarly, right-click on the Models folder and add a class file with the Name Employee.cs and then copy and paste the below code into it. This is also a very simple class having 5 properties i.e. ID, Name, Gender, Dept, and Salary.
Creating Business Layer:
Now we will create two classes that will return the list of users and the list of employees. Right-click on the Models folder and add a class file with the Name UserBL.cs and then copy and paste the below code. As you can see, here we created one method to return the list of users. In real-time, you will get the list of users from a database, but here, we are hardcoded the users list.
Similarly, right-click on the Models folder and add a class file with the Name EmployeeBL.cs and then copy and paste the below code into it. As you can see, here we created one method to return the list of employees. In real-time, you will get the list of employees from a database, but here, we are hardcoded the employees list.
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.cs and then copy and paste the following code into it. As you can see, here, the Login method takes the username and password as input parameters. Then it will check whether the username and password are valid or not. If valid, then it returns TRUE indicating the user is valid else returns FALSE indicating the user is invalid.
Create a Basic Authentication Filter in ASP.NET 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. Here, the BasicAuthenticationAttribute class is inherited from the AuthorizationFilterAttribute class and overrides the OnAuthorization method which makes this class an AuthorizationFilter and can be applied like other attributes to the action methods or at the Controller level. Here, first, we are checking the Authorization header and if it is null, we are simply returning an Unauthorized error to the client. If the Authorization header is not null, then we are taking the Authorization header value, then we decode the value and then we split the decoded value and get the user name and password. Then we call the Login method of the UserValidate class to check if the user is a valid user or not. If the user is not valid, then we return an Unauthorized error to the client else we will proceed with the request.
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 which will be applicable to all Web API controllers and action methods.
To enable the basic authentication across the entire ASP.NET 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.
Lets 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
Testing the Web API Basic Authentication using Postman
If you are new to the postman, I strongly recommended you to read the following Video, where I discussed how to download and use postman to test rest services.
Lets 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. Lets 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
Enter the username and password separated by a colon (:) in the “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, lets 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.Thats it for today. In the next Video, I am going to discuss how to implement Role-Based ASP.NET Web API Basic Authentication along with I will also discuss the advantages and disadvantages of using ASP.NET Web API Basic Authentication. Here, in this Video, I try to explain the ASP.NET Web API Basic Authentication step by step with an example. I hope you enjoy this Web API Basic AuthenticationVideo.