Foxchat.NET/Foxchat.Identity/Middleware/ClientAuthorizationMiddleware.cs

39 lines
1.2 KiB
C#
Raw Normal View History

2024-05-19 23:51:53 +02:00
using Foxchat.Core;
using Foxchat.Identity.Database;
2024-05-21 21:21:34 +02:00
using Foxchat.Identity.Utils;
2024-05-19 23:51:53 +02:00
using NodaTime;
2024-05-20 19:42:04 +02:00
namespace Foxchat.Identity.Middleware;
2024-05-19 23:51:53 +02:00
2024-05-21 20:14:52 +02:00
public class ClientAuthorizationMiddleware(
2024-05-19 23:51:53 +02:00
IdentityContext db,
IClock clock
) : IMiddleware
{
public async Task InvokeAsync(HttpContext ctx, RequestDelegate next)
{
var endpoint = ctx.GetEndpoint();
var attribute = endpoint?.Metadata.GetMetadata<AuthorizeAttribute>();
if (attribute == null)
{
await next(ctx);
return;
}
var token = ctx.GetToken();
2024-05-21 21:21:34 +02:00
if (token == null || token.Expires < clock.GetCurrentInstant())
2024-05-19 23:51:53 +02:00
throw new ApiError.Unauthorized("This endpoint requires an authenticated user.");
2024-05-21 21:21:34 +02:00
if (attribute.Scopes.Length > 0 && attribute.Scopes.Except(token.ExpandScopes()).Any())
throw new ApiError.Forbidden("This endpoint requires ungranted scopes.", attribute.Scopes.Except(token.ExpandScopes()));
2024-05-19 23:51:53 +02:00
await next(ctx);
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeAttribute(params string[] scopes) : Attribute
{
public readonly string[] Scopes = scopes;
}