Role based Authorization in .NET Core: A Beginner’s Guide with Code Snippets
Authorization plays a pivotal role in securing applications, determining who has access to specific resources. In the .NET Core ecosystem, understanding how to implement authorization and roles is crucial.
In this blog post, we’ll explore the basics of authorization and roles in .NET Core, providing code snippets and explanations to guide beginners in creating secure applications.
React similar implementation
https://medium.com/@siva.veeravarapu/role-based-authorization-and-authentication-in-react-with-auth-handlers-specific-role-based-and-466c4483a2fb
Embark on a journey of continuous learning and exploration with DotNet-FullStack-Dev. Uncover more by visiting our https://dotnet-fullstack-dev.blogspot.com reach out for further information.
Background: Understanding Authorization and Roles
Authorization is the process of determining if a user has the right permissions to access a specific resource or perform a certain action. Roles, on the other hand, are a way to group users based on their permissions. In .NET Core, these concepts are implemented through middleware and attributes.
1. Creating a .NET Core Web Application
Let’s start by creating a simple .NET Core web application.
dotnet new web -n AuthDemo
cd AuthDemo
2. Implementing Basic Authentication
In the Startup.cs
file, configure basic authentication middleware in the ConfigureServices
method
public void ConfigureServices(IServiceCollection services)
{
// Other configurations
services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
services.AddScoped<IAuthorizationHandler, RoleRequirementHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy("Admin", policy => policy.RequireRole("Admin"));
});
// Other configurations
}
Here, we’ve added a basic authentication scheme named "BasicAuthentication"
and defined a role named "Admin"
.
3. Creating a Custom Authentication Handler
Now, let’s create a custom authentication handler (BasicAuthenticationHandler.cs
) to handle basic authentication.
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Basic authentication logic
// Extract username and password from the request headers
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "Admin") // Assigning the role "Admin" for demonstration purposes
};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
In this handler, we extract the username and password from the request headers, and for demonstration purposes, we assign the role “Admin” to the user.
4. Implementing Role Authorization
Now, let’s create a custom authorization handler (RoleRequirementHandler.cs
) to handle role-based authorization.
public class RoleRequirementHandler : AuthorizationHandler<RoleRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleRequirement requirement)
{
if (context.User.IsInRole(requirement.Role))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
This handler checks if the user has the required role and succeeds if the condition is met.
5. Defining a RoleRequirement
Create a RoleRequirement.cs
file to define the RoleRequirement
class
public class RoleRequirement : IAuthorizationRequirement
{
public string Role { get; }
public RoleRequirement(string role)
{
Role = role;
}
}
This class represents the requirement for a specific role.
6. Applying Authorization in Controllers
Apply authorization to controllers or actions using attributes. For example, in a controller
[ApiController]
[Route("api/[controller]")]
[Authorize(Roles = "Admin")]
public class AdminController : ControllerBase
{
// Controller logic accessible only to users with the "Admin" role
}
Here, the [Authorize(Roles = "Admin")]
attribute restricts access to the controller or action to users with the "Admin" role.
Conclusion
Understanding authorization and roles in .NET Core is essential for building secure applications. In this beginner’s guide, we’ve walked through the basics of configuring basic authentication, creating custom authentication and authorization handlers, and applying role-based authorization to controllers.
As you continue your journey in .NET Core development, remember that authorization is a key aspect of creating robust and secure applications.
Happy coding!
One more byte : https://medium.com/@siva.veeravarapu/implementing-oauth-token-and-refresh-token-in-net-web-application-460c545753c8