.NET › Authentication & Authorization (Identity, JWT, OAuth)
How do you implement role-based authorization using the [Authorize(Roles = "...")] attribute?
IntermediateAnswer
Applying [Authorize(Roles = "Admin,Manager")] to a controller or action restricts access to only authenticated users whose ClaimsPrincipal contains a role claim matching any of the listed roles (comma-separated means OR logic), with the framework automatically returning 401 Unauthorized for unauthenticated requests or 403 Forbidden for authenticated-but-insufficiently-privileged ones.
[Authorize(Roles = "Admin")]
[HttpDelete("{id}")]
public IActionResult DeleteUser(int id) {
_userService.Delete(id);
return NoContent();
}
// Multiple roles (OR logic): [Authorize(Roles = "Admin,Manager")]Real-world example An admin dashboard's user-deletion endpoint is restricted with [Authorize(Roles = "Admin")] so that even a fully authenticated regular user attempting to call the endpoint directly receives a 403 Forbidden.