using Microsoft.AspNetCore.Mvc.Filters; namespace CampusPlusPortal.WebUI.Infrastructure.Auth; public static class ApiScope { public const string SignMeUp = "SignMeUp"; public const string BzmPlus = "BzmPlus"; } public class JwtAuthorizeAttribute : Attribute, IAuthorizationFilter { private readonly string? _scope; public JwtAuthorizeAttribute(string? scope) { _scope = scope; } public void OnAuthorization(AuthorizationFilterContext context) { //Write you code here to authorize or unauthorize the user var authHeader = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault(); if (string.IsNullOrEmpty(authHeader)) context.Result = new UnauthorizedResult(); else { var token = authHeader.Split(' ').Last(); var jwtUtils = context.HttpContext.RequestServices.GetService<IJwtUtils>(); try { var user = jwtUtils!.ValidateToken(token, true, true); if (user == null || !string.IsNullOrEmpty(_scope) && user.Scopes.All(s => !string.Equals(s, _scope, StringComparison.InvariantCultureIgnoreCase))) { context.Result = new ForbidResult(); } else { // Alles okay, Userdaten in Context schreiben context.RouteData.Values.Add("JwtApiUser", user); } } catch (Exception ex) { var logger = context.HttpContext.RequestServices.GetService<ILogger<JwtAuthorizeAttribute>>(); logger?.LogError(ex, "Token validation failed for token {token}", token); context.Result = new UnauthorizedResult(); } } } }