| | | 1 | | using ArturRios.Extensions; |
| | | 2 | | using ArturRios.Util.WebApi.Security.Attributes; |
| | | 3 | | using ArturRios.Util.WebApi.Security.Extensions; |
| | | 4 | | using Microsoft.AspNetCore.Mvc.Filters; |
| | | 5 | | |
| | | 6 | | namespace ArturRios.Util.WebApi.Security.Filters; |
| | | 7 | | |
| | | 8 | | /// <summary>Authorization filter that rejects requests with a 403 response unless the authenticated user's role |
| | | 9 | | /// is one of <paramref name="authorizedRoles"/>, or with a 401 response when no user is authenticated. Applied |
| | | 10 | | /// declaratively via <see cref="Attributes.RoleRequirementAttribute"/>, unless the action is marked with |
| | | 11 | | /// <see cref="AllowAnonymousAttribute"/>.</summary> |
| | | 12 | | /// <param name="authorizedRoles">The role values permitted to access the resource.</param> |
| | 7 | 13 | | public class RoleRequirementFilter(params int[] authorizedRoles) : IAuthorizationFilter |
| | | 14 | | { |
| | | 15 | | /// <summary>Checks the authenticated user's role against the authorized roles and short-circuits the pipeline |
| | | 16 | | /// with a 401 result when there is no user, or a 403 result when the role does not match.</summary> |
| | | 17 | | /// <param name="context">The authorization filter context for the current request.</param> |
| | | 18 | | public void OnAuthorization(AuthorizationFilterContext context) |
| | | 19 | | { |
| | 7 | 20 | | if (context.ActionDescriptor.AllowsAnonymous()) |
| | | 21 | | { |
| | 2 | 22 | | return; |
| | | 23 | | } |
| | | 24 | | |
| | 5 | 25 | | var user = context.HttpContext.GetUser(); |
| | | 26 | | |
| | 5 | 27 | | if (user is null) |
| | | 28 | | { |
| | 1 | 29 | | context.Result = AuthorizationResults.Unauthorized(); |
| | | 30 | | |
| | 1 | 31 | | return; |
| | | 32 | | } |
| | | 33 | | |
| | 4 | 34 | | if (!user.RoleId.In(authorizedRoles)) |
| | | 35 | | { |
| | 2 | 36 | | context.Result = AuthorizationResults.Forbidden(); |
| | | 37 | | } |
| | 4 | 38 | | } |
| | | 39 | | } |