- 新增 API 端 JWT 登录、refresh token 轮换和退出登录流程 - 新增 refresh token 实体、DbSet 配置和 EF Core 迁移 - 新增 PC 端授权码登录、本地全局 token 刷新、登出和鉴权服务 - 扩展统一端点模型,支持宿主过滤、角色鉴权、OpenAPI 元数据和 DI 服务处理器 - API 启用 JwtBearer 认证、Swagger UI 和认证端点注册 - PC 端注册认证服务,并按宿主过滤桌面拦截端点
74 lines
2.5 KiB
C#
74 lines
2.5 KiB
C#
using Authentication;
|
|
using Avalonia_Common.Core;
|
|
using Avalonia_Services.Core;
|
|
using Avalonia_Services.Services.AuthService;
|
|
using System;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Avalonia_PC.Authentication
|
|
{
|
|
public sealed class PcAuthEndpointService(PcGlobalTokenService tokenService) : IPcAuthEndpointService
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true,
|
|
};
|
|
|
|
public async Task<object?> AuthorizeAsync(ServiceEndpointContext ctx)
|
|
{
|
|
var request = Deserialize<PcAuthorizeRequest>(ctx.Body);
|
|
var token = await tokenService.AuthorizeAsync(request?.AuthorizationCode);
|
|
if (token is null)
|
|
{
|
|
ctx.StatusCode = 401;
|
|
return ResponseHelper.Failure(401, "授权失败");
|
|
}
|
|
|
|
return ResponseHelper.Ok(token, "授权成功");
|
|
}
|
|
|
|
public async Task<object?> RefreshAsync(ServiceEndpointContext ctx)
|
|
{
|
|
var request = Deserialize<PcRefreshRequest>(ctx.Body);
|
|
var token = request?.Token ?? ExtractBearerToken(ctx.GetHeader("Authorization"));
|
|
var refreshed = await tokenService.RefreshAsync(token);
|
|
if (refreshed is null)
|
|
{
|
|
ctx.StatusCode = 401;
|
|
return ResponseHelper.Failure(401, "授权已失效");
|
|
}
|
|
|
|
return ResponseHelper.Ok(refreshed, "刷新成功");
|
|
}
|
|
|
|
public Task<object?> LogoutAsync(ServiceEndpointContext ctx)
|
|
{
|
|
var request = Deserialize<PcLogoutRequest>(ctx.Body);
|
|
var token = request?.Token ?? ExtractBearerToken(ctx.GetHeader("Authorization"));
|
|
tokenService.Logout(token);
|
|
return Task.FromResult<object?>(ResponseHelper.Succeed("退出成功"));
|
|
}
|
|
|
|
private static T? Deserialize<T>(string? body)
|
|
{
|
|
return string.IsNullOrWhiteSpace(body)
|
|
? default
|
|
: JsonSerializer.Deserialize<T>(body, JsonOptions);
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|
|
}
|