using Authentication;
using Avalonia_Services.Core;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Avalonia_PC.Authentication
{
///
/// PC 端鉴权服务,基于全局 Token 验证用户身份,实现 。
///
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);
}
///
/// 从 Authorization 头中提取 Bearer Token。
///
/// Authorization 头的值。
/// 提取的 Token 字符串;若无法提取则返回 null。
private static string? ExtractBearerToken(string? authorization)
{
if (string.IsNullOrWhiteSpace(authorization))
{
return null;
}
string prefix = "Bearer ";
return authorization.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
? authorization[prefix.Length..].Trim()
: authorization.Trim();
}
}
}