Church.Net.API/WebAPI/Handlers/BasicAuthorizationMiddlewareResultHandler.cs
2022-10-02 09:50:42 -07:00

61 lines
2.2 KiB
C#

namespace WebAPI.Handlers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Threading.Tasks;
using WebAPI.Services;
public class BasicAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
{
private readonly AuthorizationMiddlewareResultHandler defaultHandler = new();
private readonly IServiceScopeFactory serviceScopeFactory;
public BasicAuthorizationMiddlewareResultHandler(IServiceScopeFactory serviceScopeFactory)
{
this.serviceScopeFactory = serviceScopeFactory;
}
public async Task HandleAsync(
RequestDelegate next,
HttpContext context,
AuthorizationPolicy policy,
PolicyAuthorizationResult authorizeResult)
{
// If the authorization was forbidden and the resource had a specific requirement,
// provide a custom 404 response.
if (authorizeResult.Forbidden
&& authorizeResult.AuthorizationFailure!.FailedRequirements
.OfType<Show404Requirement>().Any())
{
// Return a 404 to make it appear as if the resource doesn't exist.
context.Response.StatusCode = StatusCodes.Status404NotFound;
return;
}
if (string.IsNullOrWhiteSpace(context.Request.Headers["accessToken"]))
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
//else
//{
// using (var scope = serviceScopeFactory.CreateScope())
// {
// var service = scope.ServiceProvider.GetService<IdentityService>();
// service.UserAccessToken =;
// }
//}
// Fall back to the default implementation.
//await defaultHandler.HandleAsync(next, context, policy, authorizeResult);
await next(context);
}
}
public class Show404Requirement : IAuthorizationRequirement { }
}