How do you implement role-based authorization using the [Authorize(Roles = "...")] attribute?
Short answer
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…
Advertisement
AModel answer
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.
Likely follow-ups
- How would you require a user to have ALL of multiple roles instead of ANY?
- How does role-based authorization compare to claims-based or policy-based authorization?
Related topics