|
| 1 | +using Microsoft.AspNetCore.Authorization.Policy; |
| 2 | +using Microsoft.AspNetCore.Authorization; |
| 3 | + |
| 4 | +namespace mnestix_proxy.Authentication.ApiKeyAuthentication |
| 5 | +{ |
| 6 | + public class CustomAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler |
| 7 | + { |
| 8 | + private readonly AuthorizationMiddlewareResultHandler _defaultHandler = new(); |
| 9 | + |
| 10 | + public async Task HandleAsync(RequestDelegate next, HttpContext context, |
| 11 | + AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult) |
| 12 | + { |
| 13 | + if (authorizeResult.Forbidden) |
| 14 | + { |
| 15 | + context.Response.StatusCode = StatusCodes.Status403Forbidden; |
| 16 | + context.Response.ContentType = "application/json"; |
| 17 | + |
| 18 | + var message = "Forbidden"; |
| 19 | + if (authorizeResult.AuthorizationFailure?.FailureReasons?.Any() == true) |
| 20 | + { |
| 21 | + message = authorizeResult.AuthorizationFailure.FailureReasons |
| 22 | + .Select(r => r.Message) |
| 23 | + .FirstOrDefault() ?? message; |
| 24 | + } |
| 25 | + |
| 26 | + await context.Response.WriteAsJsonAsync(new { error = message }); |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + if (authorizeResult.Challenged) |
| 31 | + { |
| 32 | + context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
| 33 | + context.Response.ContentType = "application/json"; |
| 34 | + |
| 35 | + await context.Response.WriteAsJsonAsync(new |
| 36 | + { |
| 37 | + error = "Unauthorized: You must provide valid authentication credentials." |
| 38 | + }); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + // Proceed normally |
| 43 | + await _defaultHandler.HandleAsync(next, context, policy, authorizeResult); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | +} |
0 commit comments