feat(auth): 添加统一 API 和 PC 认证端点

- 新增 API 端 JWT 登录、refresh token 轮换和退出登录流程
- 新增 refresh token 实体、DbSet 配置和 EF Core 迁移
- 新增 PC 端授权码登录、本地全局 token 刷新、登出和鉴权服务
- 扩展统一端点模型,支持宿主过滤、角色鉴权、OpenAPI 元数据和 DI 服务处理器
- API 启用 JwtBearer 认证、Swagger UI 和认证端点注册
- PC 端注册认证服务,并按宿主过滤桌面拦截端点
This commit is contained in:
2026-05-15 17:35:07 +08:00
parent c5f741e6a4
commit a9abd90874
26 changed files with 1295 additions and 31 deletions
@@ -0,0 +1,123 @@
using Avalonia_Common.Core;
using Avalonia_EFCore.Database;
using Avalonia_EFCore.Models;
using Avalonia_Services.Core;
using Avalonia_Services.Services.AuthService;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace Avalonia_API.Authentication
{
public sealed class ApiAuthEndpointService(
AppDataContext db,
JwtTokenService jwtTokenService,
RefreshTokenService refreshTokenService) : IApiAuthEndpointService
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
};
public async Task<object?> LoginAsync(ServiceEndpointContext ctx)
{
var request = Deserialize<ApiLoginRequest>(ctx.Body);
if (string.IsNullOrWhiteSpace(request?.Account))
{
ctx.StatusCode = 400;
return ResponseHelper.Failure(400, "账号不能为空");
}
var user = await db.Users.FirstOrDefaultAsync(
x => x.Email == request.Account || x.Name == request.Account);
if (user is null)
{
user = new UserEntity
{
Name = request.Account,
Email = request.Account.Contains('@') ? request.Account : null,
};
db.Users.Add(user);
await db.SaveChangesAsync();
}
var roles = NormalizeRoles(request.Roles);
var accessToken = jwtTokenService.CreateAccessToken(user, roles);
var refreshToken = await refreshTokenService.CreateAsync(
user.Id,
ctx.GetHeader("User-Agent"),
GetRemoteIpAddress(ctx));
return ResponseHelper.Ok(new AuthTokenResponse(
accessToken.Token,
refreshToken.Token,
accessToken.ExpiresAt,
refreshToken.Entity.ExpiresAt,
roles), "登录成功");
}
public async Task<object?> RefreshAsync(ServiceEndpointContext ctx)
{
var request = Deserialize<ApiRefreshTokenRequest>(ctx.Body);
var rotated = await refreshTokenService.RotateAsync(
request?.RefreshToken,
ctx.GetHeader("User-Agent"),
GetRemoteIpAddress(ctx));
if (rotated is null)
{
ctx.StatusCode = 401;
return ResponseHelper.Failure(401, "刷新 token 无效或已过期");
}
var user = await db.Users.FindAsync(rotated.Value.Entity.UserId);
if (user is null)
{
ctx.StatusCode = 401;
return ResponseHelper.Failure(401, "用户不存在");
}
var roles = new[] { "Admin" };
var accessToken = jwtTokenService.CreateAccessToken(user, roles);
return ResponseHelper.Ok(new AuthTokenResponse(
accessToken.Token,
rotated.Value.Token,
accessToken.ExpiresAt,
rotated.Value.Entity.ExpiresAt,
roles), "刷新成功");
}
public async Task<object?> LogoutAsync(ServiceEndpointContext ctx)
{
var request = Deserialize<ApiLogoutRequest>(ctx.Body);
await refreshTokenService.RevokeAsync(request?.RefreshToken);
return ResponseHelper.Succeed("退出成功");
}
private static T? Deserialize<T>(string? body)
{
return string.IsNullOrWhiteSpace(body)
? default
: JsonSerializer.Deserialize<T>(body, JsonOptions);
}
private static string? GetRemoteIpAddress(ServiceEndpointContext ctx)
{
return ctx.Items.TryGetValue("HttpContext", out var value) && value is HttpContext httpContext
? httpContext.Connection.RemoteIpAddress?.ToString()
: null;
}
private static string[] NormalizeRoles(string[]? roles)
{
var normalized = roles?
.Where(role => !string.IsNullOrWhiteSpace(role))
.Select(role => role.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
return normalized is { Length: > 0 } ? normalized : ["Admin"];
}
}
}
+15
View File
@@ -0,0 +1,15 @@
namespace Avalonia_API.Authentication
{
public sealed class JwtOptions
{
public string Issuer { get; set; } = "Avalonia-API";
public string Audience { get; set; } = "Avalonia-Client";
public string SigningKey { get; set; } = "change-this-development-signing-key-at-least-32-bytes";
public int AccessTokenMinutes { get; set; } = 60;
public int RefreshTokenDays { get; set; } = 30;
}
}
@@ -0,0 +1,43 @@
using Avalonia_EFCore.Models;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Avalonia_API.Authentication
{
public sealed class JwtTokenService(IOptions<JwtOptions> options)
{
private readonly JwtOptions _options = options.Value;
public (string Token, DateTime ExpiresAt) CreateAccessToken(UserEntity user, IReadOnlyCollection<string> roles)
{
var expiresAt = DateTime.UtcNow.AddMinutes(_options.AccessTokenMinutes);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
new(ClaimTypes.Name, user.Name ?? user.Email ?? $"user-{user.Id}"),
new("auth_type", "api-jwt"),
};
foreach (var role in roles.Where(role => !string.IsNullOrWhiteSpace(role)).Distinct(StringComparer.OrdinalIgnoreCase))
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SigningKey));
var credentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
var jwt = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: expiresAt,
signingCredentials: credentials);
return (new JwtSecurityTokenHandler().WriteToken(jwt), expiresAt);
}
}
}
@@ -0,0 +1,84 @@
using Avalonia_EFCore.Database;
using Avalonia_EFCore.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.Security.Cryptography;
using System.Text;
namespace Avalonia_API.Authentication
{
public sealed class RefreshTokenService(AppDataContext db, IOptions<JwtOptions> options)
{
private readonly JwtOptions _options = options.Value;
public async Task<(string Token, ApiRefreshTokenEntity Entity)> CreateAsync(
int userId,
string? device,
string? ipAddress,
CancellationToken cancellationToken = default)
{
var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64));
var entity = new ApiRefreshTokenEntity
{
UserId = userId,
TokenHash = HashToken(token),
ExpiresAt = DateTime.UtcNow.AddDays(_options.RefreshTokenDays),
Device = device,
IpAddress = ipAddress,
};
db.ApiRefreshTokens.Add(entity);
await db.SaveChangesAsync(cancellationToken);
return (token, entity);
}
public async Task<ApiRefreshTokenEntity?> FindActiveAsync(string? token, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(token))
{
return null;
}
var hash = HashToken(token);
var entity = await db.ApiRefreshTokens.FirstOrDefaultAsync(x => x.TokenHash == hash, cancellationToken);
return entity?.IsActive == true ? entity : null;
}
public async Task RevokeAsync(string? token, CancellationToken cancellationToken = default)
{
var entity = await FindActiveAsync(token, cancellationToken);
if (entity is null)
{
return;
}
entity.RevokedAt = DateTime.UtcNow;
await db.SaveChangesAsync(cancellationToken);
}
public async Task<(string Token, ApiRefreshTokenEntity Entity)?> RotateAsync(
string? token,
string? device,
string? ipAddress,
CancellationToken cancellationToken = default)
{
var current = await FindActiveAsync(token, cancellationToken);
if (current is null)
{
return null;
}
var next = await CreateAsync(current.UserId, device, ipAddress, cancellationToken);
current.RevokedAt = DateTime.UtcNow;
current.ReplacedByTokenHash = next.Entity.TokenHash;
await db.SaveChangesAsync(cancellationToken);
return next;
}
private static string HashToken(string token)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(token));
return Convert.ToHexString(bytes);
}
}
}