using Authentication; using Avalonia_Services.Core; using System; using System.Security.Claims; using System.Threading.Tasks; namespace Avalonia_PC.Authentication { public sealed class PcAuthService(PcGlobalTokenService tokenService) : IAuthService { public async Task AuthenticateAsync(ServiceEndpointContext context) { var token = ExtractBearerToken(context.GetHeader("Authorization")); if (!await tokenService.ValidateAsync(token)) { return null; } var identity = new ClaimsIdentity( [ new Claim(ClaimTypes.NameIdentifier, "pc-local"), new Claim(ClaimTypes.Name, "PC授权用户"), new Claim(ClaimTypes.Role, "SuperAdmin"), new Claim(ClaimTypes.Role, "Admin"), new Claim("auth_type", "pc-global-token"), ], "pc-global-token"); return new ClaimsPrincipal(identity); } public Task AuthorizeAsync(ClaimsPrincipal user, string policy) { return Task.FromResult(user.Identity?.IsAuthenticated == true); } private static string? ExtractBearerToken(string? authorization) { if (string.IsNullOrWhiteSpace(authorization)) { return null; } const string prefix = "Bearer "; return authorization.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? authorization[prefix.Length..].Trim() : authorization.Trim(); } } }