Role-Based Basic Authentication in Web API

Role-Based Basic Authentication is a security mechanism that not only authenticates users but also checks their roles or permissions before granting access to specific resources in a Web API. In this comprehensive lesson, we’ll explore how to implement Role-Based Basic Authentication in ASP.NET Web API with SQL Server for user management, and provide code examples to demonstrate the process.

Prerequisites

Before proceeding, make sure you have the following prerequisites:

  1. SQL Server database for user management.
  2. Basic understanding of ASP.NET Web API and SQL Server.

Implementation Steps

1. Database Setup

Create a SQL Server database to store user information. Create two tables: Users to store user credentials and UserRoles to associate users with roles.

2. User Registration

When a user registers, store their credentials (username and password hash) in the Users table.

public void RegisterUser(string username, string password)
{
    string salt = GenerateSalt(); // Generate a random salt
    string passwordHash = HashPassword(password, salt); // Hash the password with the salt
    // Store username, passwordHash, and salt in the Users table
}

3. Role Assignment

Create roles in the UserRoles table and associate users with their respective roles.

public void AssignUserRole(string username, string roleName)
{
    // Associate the user with the specified role in the UserRoles table
}

4. Authentication Middleware

Implement an authentication middleware that checks for Basic Authentication credentials in the Authorization header and verifies the user’s role.

public class RoleBasedAuthenticationMiddleware
{
    private readonly RequestDelegate _next;

    public RoleBasedAuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        string authHeader = context.Request.Headers["Authorization"];
        if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Basic "))
        {
            string encodedCredentials = authHeader.Substring("Basic ".Length).Trim();
            string credentials = Encoding.UTF8.GetString(Convert.FromBase64String(encodedCredentials));
            string[] parts = credentials.Split(':');
            string username = parts[0];
            string password = parts[1];

            // Validate username and password against the database
            if (IsValidUser(username, password))
            {
                // Check the user's role
                if (IsUserInRole(username, "Admin"))
                {
                    // User is authorized as an admin
                    await _next.Invoke(context);
                    return;
                }
            }
        }

        // Unauthorized access
        context.Response.Headers["WWW-Authenticate"] = "Basic realm=\"Your API\"";
        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
    }
}

5. Securing API Endpoints

Apply the RoleBasedAuthenticationMiddleware to the API endpoints that require role-based authentication.

[Route("api/admin")]
[Authorize(Roles = "Admin")]
public class AdminController : ApiController
{
    [HttpGet]
    [Route("data")]
    public IHttpActionResult GetAdminData()
    {
        // This endpoint is secured with Role-Based Basic Authentication
        // Only authenticated users with the "Admin" role can access it
        var data = GetAdminSensitiveData();
        return Ok(data);
    }
}

In this example, the [Authorize(Roles = "Admin")] attribute is applied to the AdminController. This means that only authenticated users with the “Admin” role can access the GetAdminData endpoint.


In an ASP.NET Web API application that uses Role-Based Basic Authentication with SQL Server, you can access the user’s role name within a controller using the User property of the ApiController class. Here’s how you can retrieve the user’s role name:

using System.Web.Http;

public class MyController : ApiController
{
    public IHttpActionResult MyAction()
    {
        // Get the user's role name
        string roleName = User.Identity.Name;

        // Now you can use the roleName in your controller logic
        if (string.Equals(roleName, "Admin", StringComparison.OrdinalIgnoreCase))
        {
            // User has the "Admin" role
            // Implement your logic for admin users
        }
        else if (string.Equals(roleName, "User", StringComparison.OrdinalIgnoreCase))
        {
            // User has the "User" role
            // Implement your logic for regular users
        }
        else
        {
            // User doesn't have a recognized role
            // Handle it accordingly
        }

        // Continue with your controller logic

        return Ok("Action completed");
    }
}

In this example, we use User.Identity.Name to retrieve the user’s role name. You can then use this role name in your controller logic to determine what actions or data the user is authorized to access based on their role.

Conclusion

Role-Based Basic Authentication in ASP.NET Web API with SQL Server adds an extra layer of security by controlling access to resources based on user roles or permissions. By following the steps outlined in this lesson and implementing the provided code examples, you can create a role-based authentication system that ensures only authorized users with specific roles can access protected resources in your API.