| | | 1 | | using ArturRios.Extensions; |
| | | 2 | | using ArturRios.Output; |
| | | 3 | | using ArturRios.Util.Http; |
| | | 4 | | using ArturRios.Util.WebApi.Security.Attributes; |
| | | 5 | | using ArturRios.Util.WebApi.Security.Records; |
| | | 6 | | using Microsoft.AspNetCore.Mvc; |
| | | 7 | | using Microsoft.AspNetCore.Mvc.Filters; |
| | | 8 | | |
| | | 9 | | namespace ArturRios.Util.WebApi.Security.Filters; |
| | | 10 | | |
| | | 11 | | /// <summary>Authorization filter that rejects requests with a 403 response unless the authenticated user's role |
| | | 12 | | /// is one of <paramref name="authorizedRoles"/>. Applied declaratively via <see cref="Attributes.RoleRequirementAttribu |
| | | 13 | | /// unless the action is marked with <see cref="AllowAnonymousAttribute"/>.</summary> |
| | | 14 | | /// <param name="authorizedRoles">The role values permitted to access the resource.</param> |
| | 4 | 15 | | public class RoleRequirementFilter(params int[] authorizedRoles) : IAuthorizationFilter |
| | | 16 | | { |
| | | 17 | | /// <summary>Checks the authenticated user's role against the authorized roles and short-circuits the pipeline with |
| | | 18 | | /// <param name="context">The authorization filter context for the current request.</param> |
| | | 19 | | public void OnAuthorization(AuthorizationFilterContext context) |
| | 4 | 20 | | { |
| | 4 | 21 | | var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any(); |
| | | 22 | | |
| | 4 | 23 | | if (allowAnonymous) |
| | 1 | 24 | | { |
| | 1 | 25 | | return; |
| | | 26 | | } |
| | | 27 | | |
| | 3 | 28 | | var user = context.HttpContext.Items["User"] as AuthenticatedUser; |
| | | 29 | | |
| | 3 | 30 | | var authorized = false; |
| | | 31 | | |
| | 3 | 32 | | if (user is not null) |
| | 2 | 33 | | { |
| | 2 | 34 | | authorized = user.Role.In(authorizedRoles); |
| | 2 | 35 | | } |
| | | 36 | | |
| | 3 | 37 | | if (authorized) |
| | 1 | 38 | | { |
| | 1 | 39 | | return; |
| | | 40 | | } |
| | | 41 | | |
| | 2 | 42 | | var output = ProcessOutput.New.WithError("You do not have permission to access this resource"); |
| | | 43 | | |
| | 2 | 44 | | context.Result = new ObjectResult(output) { StatusCode = HttpStatusCodes.Forbidden }; |
| | 4 | 45 | | } |
| | | 46 | | } |