| | | 1 | | using ArturRios.Util.WebApi.Security.Records; |
| | | 2 | | using Microsoft.AspNetCore.Http; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | using Microsoft.AspNetCore.Mvc.Filters; |
| | | 5 | | |
| | | 6 | | namespace ArturRios.Util.WebApi.Security.Attributes; |
| | | 7 | | |
| | | 8 | | /// <summary>Rejects requests with a 401 response unless an <see cref="AuthenticatedUser"/> was attached to the |
| | | 9 | | /// context (typically by <see cref="Security.Middleware.AuthenticationMiddleware"/>), unless the action is marked with |
| | | 10 | | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] |
| | | 11 | | public class AuthorizeAttribute : Attribute, IAuthorizationFilter |
| | | 12 | | { |
| | | 13 | | /// <summary>Checks for an authenticated user on the context and short-circuits the pipeline with a 401 result if no |
| | | 14 | | /// <param name="context">The authorization filter context for the current request.</param> |
| | | 15 | | public void OnAuthorization(AuthorizationFilterContext context) |
| | 0 | 16 | | { |
| | 0 | 17 | | var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any(); |
| | | 18 | | |
| | 0 | 19 | | if (allowAnonymous) |
| | 0 | 20 | | { |
| | 0 | 21 | | return; |
| | | 22 | | } |
| | | 23 | | |
| | 0 | 24 | | var user = (AuthenticatedUser?)context.HttpContext.Items["User"]; |
| | | 25 | | |
| | 0 | 26 | | if (user is null) |
| | 0 | 27 | | { |
| | 0 | 28 | | context.Result = |
| | 0 | 29 | | new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized }; |
| | 0 | 30 | | } |
| | 0 | 31 | | } |
| | | 32 | | } |