Role-based Authorization
Overview
Role-based authorization checks if the authenticated user belongs to specific roles before granting access.
Implementation
1. Add Roles to Claims
var claims = new[]
{
new Claim(ClaimTypes.Name, "john@example.com"),
new Claim(ClaimTypes.Role, "Admin"),
new Claim(ClaimTypes.Role, "User") // User can have multiple roles
};
2. Protect Endpoints with Roles
Minimal APIs
app.MapGet("/api/admin", () => "Admin only content")
.RequireAuthorization(policy => policy.RequireRole("Admin"));
app.MapGet("/api/users", () => "User content")
.RequireAuthorization(policy => policy.RequireRole("User", "Admin"));
Controllers
[Authorize(Roles = "Admin")]
public class AdminController : ControllerBase
{
[HttpGet]
public IActionResult GetAdminData()
{
return Ok("Admin data");
}
}
[Authorize(Roles = "User,Admin")] // OR logic
public IActionResult GetUserData()
{
return Ok("User data");
}
3. Check Roles in Code
app.MapGet("/api/data", (HttpContext context) =>
{
if (context.User.IsInRole("Admin"))
{
return Results.Ok("Admin view");
}
if (context.User.IsInRole("User"))
{
return Results.Ok("User view");
}
return Results.Forbid();
}).RequireAuthorization();
Role Management
Add Roles During Registration
public class UserService
{
public async Task<User> CreateUserAsync(string email, string password, string[] roles)
{
// Hash password
// Save to database with roles
var user = new User
{
Email = email,
Roles = roles // ["User", "Admin"]
};
return user;
}
}
Generate Token with Roles
public string GenerateToken(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
};
// Add all roles as separate claims
foreach (var role in user.Roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Best Practices
- Principle of Least Privilege: Assign minimal necessary roles
- Role Naming: Use clear, descriptive names (Admin, Editor, Viewer)
- Multiple Roles: Users can have multiple roles
- Role Hierarchies: Consider if roles imply other roles
Limitations
- Not granular enough for complex scenarios
- Harder to maintain with many roles
- Consider policy-based authorization for complex requirements
Interview Questions
Q: What's the difference between role-based and claims-based authorization? A: Roles are a type of claim. Role-based is simpler but less flexible. Claims-based allows any custom claim for authorization decisions.
Q: Can a user have multiple roles? A: Yes, a user can have multiple roles. Add multiple role claims to the identity.