61 lines
2.1 KiB
C#
61 lines
2.1 KiB
C#
|
|
using Authentication;
|
||
|
|
using Avalonia_Services.Core;
|
||
|
|
using System;
|
||
|
|
using System.Security.Claims;
|
||
|
|
using System.Threading.Tasks;
|
||
|
|
|
||
|
|
namespace Avalonia_PC.Authentication
|
||
|
|
{
|
||
|
|
/// <summary>
|
||
|
|
/// PC 端鉴权服务,基于全局 Token 验证用户身份,实现 <see cref="IAuthService"/>。
|
||
|
|
/// </summary>
|
||
|
|
public sealed class PcAuthService(PcGlobalTokenService tokenService) : IAuthService
|
||
|
|
{
|
||
|
|
/// <inheritdoc />
|
||
|
|
public async Task<ClaimsPrincipal?> 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);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <inheritdoc />
|
||
|
|
public Task<bool> AuthorizeAsync(ClaimsPrincipal user, string policy)
|
||
|
|
{
|
||
|
|
return Task.FromResult(user.Identity?.IsAuthenticated == true);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// 从 Authorization 头中提取 Bearer Token。
|
||
|
|
/// </summary>
|
||
|
|
/// <param name="authorization">Authorization 头的值。</param>
|
||
|
|
/// <returns>提取的 Token 字符串;若无法提取则返回 null。</returns>
|
||
|
|
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();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|