using System.Security.Claims; using AspNetCore.Authentication.ApiKey; using Microsoft.AspNetCore.Authorization; using Microsoft.EntityFrameworkCore; namespace NejCommon.Authorization; public partial class PermissionHandler : AuthorizationHandler { protected override async Task HandleRequirementAsync( AuthorizationHandlerContext context, PermissionRequirement requirement) { if (context.Resource is not HttpContext http) return; var companyId = http.GetRouteValue("companyId")?.ToString(); if (companyId == null) { context.Succeed(requirement); return; } var authType = context.User.Identity?.AuthenticationType; if (authType == null) return; bool allowed; if (authType == ApiKeyDefaults.AuthenticationScheme) { var id = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (id == null) return; allowed = await CheckApiKeyPermission(id, companyId, requirement.Permission); } else { Console.WriteLine(string.Join(',', context.User.Claims.Select(c => $"{c.Type}: {c.Value}"))); var sub = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (sub == null) return; allowed = await CheckUserPermission(sub, companyId, requirement.Permission); } if (allowed) context.Succeed(requirement); } }