summary refs log tree commit diff
path: root/extra/admin-api/Spacebar.AdminAPI/Middleware
diff options
context:
space:
mode:
authorEmma [it/its]@Rory& <root@rory.gay>2024-12-27 05:48:14 +0100
committerEmma [it/its]@Rory& <root@rory.gay>2025-10-05 21:33:50 +0200
commita632666203e7c6c67fdb3bcf1809a591b1d0edf1 (patch)
tree21059211df2229637a425089e4480b21cd6ffc1a /extra/admin-api/Spacebar.AdminAPI/Middleware
parentUpdate dependencies (diff)
downloadserver-ts-a632666203e7c6c67fdb3bcf1809a591b1d0edf1.tar.xz
Rewrite access tokens, initial admin api
Diffstat (limited to 'extra/admin-api/Spacebar.AdminAPI/Middleware')
-rw-r--r--extra/admin-api/Spacebar.AdminAPI/Middleware/AuthenticationMiddleware.cs53
1 files changed, 53 insertions, 0 deletions
diff --git a/extra/admin-api/Spacebar.AdminAPI/Middleware/AuthenticationMiddleware.cs b/extra/admin-api/Spacebar.AdminAPI/Middleware/AuthenticationMiddleware.cs
new file mode 100644

index 000000000..400928e51 --- /dev/null +++ b/extra/admin-api/Spacebar.AdminAPI/Middleware/AuthenticationMiddleware.cs
@@ -0,0 +1,53 @@ +using System.Buffers.Text; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Cryptography; +using System.Text; +using ArcaneLibs.Extensions; +using Microsoft.EntityFrameworkCore.Internal; +using Microsoft.IdentityModel.Tokens; +using Spacebar.AdminAPI.Extensions; +using Spacebar.Db.Contexts; + +namespace Spacebar.AdminAPI.Middleware; + +public class AuthenticationMiddleware(RequestDelegate next) { + public async Task Invoke(HttpContext context) { + if(Environment.GetEnvironmentVariable("SB_ADMIN_API_DISABLE_AUTH") == "true") { + await next(context); + return; + } + + if (!context.Request.Headers.ContainsKey("Authorization")) { + context.Response.StatusCode = 401; + await context.Response.WriteAsync("Authorization header is missing"); + return; + } + + var token = context.Request.Headers["Authorization"].ToString().Split(' ').Last(); + + var handler = new JwtSecurityTokenHandler(); + var secretFile = File.ReadAllText("../../../jwt.key.pub"); + var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + key.ImportFromPem(secretFile); + + var res = await handler.ValidateTokenAsync(token, new TokenValidationParameters { + IssuerSigningKey = new ECDsaSecurityKey(key), + ValidAlgorithms = new[] { "ES512" }, + LogValidationExceptions = true, + // These are required to be false for the token to be valid as they aren't provided by the token + ValidateIssuer = false, + ValidateLifetime = false, + ValidateAudience = false, + }); + + if (!res.IsValid) { + context.Response.StatusCode = 401; + await context.Response.WriteAsync("Invalid token"); + return; + } + + Console.WriteLine(res.ClaimsIdentity.Claims.Select(x => $"{x.Type} : {x.Value}").ToJson()); + + await next(context); + } +} \ No newline at end of file