Loading

ASP.NET Web API

How to implement Role-Based Basic Authentication in ASP.NET Web API?. The Complete ASP.NET Web API Developer Course 2023 [Videos].

In this article, I am going to discuss how to implement the Role-Based Basic Authentication in ASP.NET Web API Applications. Please read our last article before proceeding to this article, where we discussed How to implement ASP.NET Web API Basic Authentication with an example. As part of this article, we are going to discuss the following pointers related to authentication and authorization.

  1. Why do we need Role-Based Authentication?
  2. How to Implement Role-Based Basic Authentication in Web API?
  3. Testing the Role-Based Basic Authentication using Postman.
  4. What are the advantages and disadvantages of using BASIC Authentication in Web API?
Why do we need Role-Based Authentication?

Let us understand this with an example. As shown in the below image, we have three resources i.e. GetAllMaleEmployeesGetAllFemaleEmployees, and GetAllEmployees in our service.

Role-Based Basic Authentication in Web API

In our application, let say we have two types of Roles i.e. Admin and Superadmin and as per our business requirement,

  1. Only the users who have the Role Admin can access only to the GetAllMaleEmployees resource.
  2. The users who have the Role Superadmin can access only the GetAllFemaleEmployees resource.
  3. The GetAllEmployees resource can be accessed by both the Admin and Superadmin resource.

In order to achieve this, we need to implement Role-Based Authentication in ASP.NET Web API.

Implementing Role-Based Basic Authentication in Web API.

First, create an empty Web API application with the name RoleBasedBasicAuthenticationWEBAPI. Then Add the following User and Employee model to the Models folder

User.cs
namespace RoleBasedBasicAuthenticationWEBAPI.Models
{
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Roles { get; set; }
public string Email { get; set; }
}
}
Employee.cs
namespace RoleBasedBasicAuthenticationWEBAPI.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 add the UserBL and EmployeeBL class file within the Models folder.

UserBL.cs
namespace RoleBasedBasicAuthenticationWEBAPI.Models
{
public class UsersBL
{
public List<User> GetUsers()
{
// In Realtime you need to get the data from any persistent storage
// For Simplicity of this demo and to keep focus on Basic Authentication
// Here we are hardcoded the data
List<User> userList = new List<User>();
userList.Add(new User()
{
ID = 101,
UserName = "AdminUser",
Password = "123456",
Roles = "Admin",
Email = "Admin@a.com"
});
userList.Add(new User()
{
ID = 102,
UserName = "BothUser",
Password = "abcdef",
Roles = "Admin,Superadmin",
Email = "BothUser@a.com"
});
userList.Add(new User()
{
ID = 103,
UserName = "SuperadminUser",
Password = "Password@123",
Roles = "Superadmin",
Email = "Superadmin@a.com"
});
return userList;
}
}
}
EmployeeBL.cs
namespace RoleBasedBasicAuthenticationWEBAPI.Models
{
public class EmployeeBL
{
public List<Employee> GetEmployees()
{
// In Realtime you need to get the data from any persistent storage
// For Simplicity of this demo and to keep 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 add one more class file with the name UserValidate and copy and paste the following code.

UserValidate.cs
namespace RoleBasedBasicAuthenticationWEBAPI.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);
}
//This method is used to return the User Details
public static User GetUserDetails(string username, string password)
{
UsersBL userBL = new UsersBL();
return userBL.GetUsers().FirstOrDefault(user =>
user.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)
&& user.Password == password);
}
}
}

Now create the BasicAuthenticationAttribute which will implement the AuthorizationFilterAttribute where we will put the logic for role-based basic authentication.

BasicAuthenticationAttribute.cs
using System;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace RoleBasedBasicAuthenticationWEBAPI.Models
{
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
private const string Realm = "My Realm";
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized)
{
actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm="{0}"", Realm));
}
}
else
{























}
}
}
}<b>
</b>

Now we will create our custom Authorize Attribute which will inherit from AuthorizeAttribute where we will implement the logic to return an appropriate response when the Authorization failed.

MyAuthorizeAttribute.cs
namespace RoleBasedBasicAuthenticationWEBAPI.Models
{
public class MyAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{



protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(actionContext);
}
else
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
}







}
}
}

Lets create a Web API 2 Empty Controller with the name EmployeeController and copy and paste the following code.

using RoleBasedBasicAuthenticationWEBAPI.Models;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
namespace RoleBasedBasicAuthenticationWEBAPI.Controllers
{
public class EmployeeController : ApiController
{
[BasicAuthentication]
[MyAuthorize(Roles = "Admin")]
[Route("api/AllMaleEmployees")]
public HttpResponseMessage GetAllMaleEmployees()
{
var identity = (ClaimsIdentity)User.Identity;
//Getting the ID value
var ID = identity.Claims
.FirstOrDefault(c => c.Type == "ID").Value;
//Getting the Email value
var Email = identity.Claims
.FirstOrDefault(c => c.Type == "Email").Value;
//Getting the Username value
var username = identity.Name;
//Getting the Roles only if you set the roles in the claims
//var Roles = identity.Claims
// .Where(c => c.Type == ClaimTypes.Role)
// .Select(c => c.Value).ToArray();
var EmpList = new EmployeeBL().GetEmployees().Where(e => e.Gender.ToLower() == "male").ToList();
return Request.CreateResponse(HttpStatusCode.OK, EmpList);
}
[BasicAuthentication]
[MyAuthorize(Roles = "Superadmin")]
[Route("api/AllFemaleEmployees")]
public HttpResponseMessage GetAllFemaleEmployees()
{
var EmpList = new EmployeeBL().GetEmployees().Where(e => e.Gender.ToLower() == "female").ToList();
return Request.CreateResponse(HttpStatusCode.OK, EmpList);
}
[BasicAuthentication]
[MyAuthorize(Roles = "Admin,Superadmin")]
[Route("api/AllEmployees")]
public HttpResponseMessage GetAllEmployees()
{
var EmpList = new EmployeeBL().GetEmployees();
return Request.CreateResponse(HttpStatusCode.OK, EmpList);
}
}
}

Thats it. We have done with our implementation.

Testing Role-Based Basic Authentication in Web API 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.

We need to pass the username and password in 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 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. Let first generate the Base64 encoded string for the user AdminUser as shown in the below image

Testing Role-Based Basic Authentication in Web API using Postman

Once you generated 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

The role Admin has been assigned to the AdminUser. So he can access only the following two resources

/api/AllMaleEmployees
/api/AllEmployees

But he cannot access the following resource

/api/AllFemaleEmployees

Let proofs this using the Postman.

/api/AllMaleEmployees

Role-Based Web API Authentication

Here we got the response 200 OK.

/api/AllEmployees

Role-Based Web API Authentication

Here we also got the response 200 OK as expected.

/api/AllFemaleEmployees

Role-Based Basic Authentication in WEB API

As you can see, here we got the response as 403 Forbidden which means the user is authenticated but not authorized to access the above resource. Similarly, you can test the other users.  

Advantages and disadvantages of Basic Authentication in Web API.
Advantages:
  1. Internet standard.
  2. Supported by all major browsers.
  3. Relatively simple protocol.
Disadvantages:
  1. User credentials are sent in the request.
  2. Credentials are sent as plaintext.
  3. Credentials are sent with every request.
  4. No way to log out, except by ending the browser session.
  5. Vulnerable to cross-site request forgery (CSRF); requires anti-CSRF measures.

In the next Video, I am going to discuss how to consume the Web API from JavaScript and C# clients. Here, in this Video, I try to explain the Role-Based Basic Authentication in Web API Applications step by step with an example. I hope now you understood the need and use Role-Based Authentication in Web API. 

See All

Comments (557 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Web API / Blog

What is ASP.NET Web API Application?

In this ASP.NET Web API Tutorials series, I covered all the features of ASP.NET Web API. You will learn from basic to advance level features of ASP.NET Web API. The term API stands for “Application Programming Interface” and ASP.NET Web API is a framework provided by Microsoft which makes it easy to build Web APIs, i.e. it is used to develop HTTP-based web services on the top of .NET Framework.
3-Feb-2022 /34 /557

ASP.NET Web API / Blog

How to creat ASP.NET Web API Application using Visual Studio?

In this article, I am going to discuss the step-by-step procedure for Creating ASP.NET Web API Application. Please read our previous article before proceeding to this article where we gave an overview of the ASP.NET Web API framework. As part of this article, we ate going to discuss the following pointers.
3-Feb-2022 /34 /557

ASP.NET Web API / Blog

How to add Swagger in Web API Application?

In this article, I am going to discuss how to add Swagger in Web API Application to document and test restful Web API services. Please read our previous article where we discussed How to Create an ASP.NET Web API Application step by step before proceeding to this article as we are going to work with the same example. As part of this article, we are going to discuss the following pointers.
3-Feb-2022 /34 /557