add more authentication code

This commit is contained in:
sam 2024-05-19 23:51:53 +02:00
parent aca83fa1ef
commit 04b7cf624d
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
7 changed files with 151 additions and 55 deletions

View file

@ -0,0 +1,38 @@
using System.Net;
using Foxchat.Core;
using Foxchat.Identity.Database;
using NodaTime;
namespace Foxchat.Identity.Authorization;
public class AuthorizationMiddleware(
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();
if (token == null || token.Expires > clock.GetCurrentInstant())
throw new ApiError.Unauthorized("This endpoint requires an authenticated user.");
if (attribute.Scopes.Length > 0 && attribute.Scopes.Except(token.Scopes).Any())
throw new ApiError.Forbidden("This endpoint requires ungranted scopes.", attribute.Scopes.Except(token.Scopes));
await next(ctx);
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeAttribute(params string[] scopes) : Attribute
{
public readonly string[] Scopes = scopes;
}