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:
@@ -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"];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,13 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="8.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
using Avalonia_EFCore.Database;
|
||||
using Avalonia_API.Authentication;
|
||||
using Avalonia_EFCore.Database;
|
||||
using Avalonia_Services.Core;
|
||||
using Avalonia_Services.Endpoints;
|
||||
using Avalonia_Services.Services;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Avalonia_Services.Services.AuthService;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
namespace Avalonia_API.Configuration
|
||||
{
|
||||
@@ -31,9 +34,35 @@ namespace Avalonia_API.Configuration
|
||||
// ---- 业务服务 ----
|
||||
services.AddScoped<WeatherForecastService>();
|
||||
|
||||
// ---- API 鉴权 ----
|
||||
var jwtSection = configuration.GetSection("Jwt");
|
||||
services.Configure<JwtOptions>(jwtSection);
|
||||
var jwtOptions = jwtSection.Get<JwtOptions>() ?? new JwtOptions();
|
||||
services
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtOptions.Issuer,
|
||||
ValidAudience = jwtOptions.Audience,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SigningKey)),
|
||||
ClockSkew = TimeSpan.FromMinutes(1),
|
||||
};
|
||||
});
|
||||
services.AddAuthorization();
|
||||
services.AddScoped<JwtTokenService>();
|
||||
services.AddScoped<RefreshTokenService>();
|
||||
services.AddScoped<IApiAuthEndpointService, ApiAuthEndpointService>();
|
||||
|
||||
// ---- 统一端点 ----
|
||||
var endpointBuilder = new ServiceEndpointBuilder();
|
||||
AppEndpoints.Configure(endpointBuilder);
|
||||
AuthEndpoints.ConfigureApi(endpointBuilder);
|
||||
var endpoints = endpointBuilder.Build();
|
||||
services.AddSingleton(endpoints);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Avalonia_Services.Core;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using AspNetCoreFilterContext = Microsoft.AspNetCore.Http.EndpointFilterInvocationContext;
|
||||
using AspNetCoreFilterDelegate = Microsoft.AspNetCore.Http.EndpointFilterDelegate;
|
||||
// 解决与 ASP.NET Core 同名类型的冲突
|
||||
@@ -22,7 +23,7 @@ namespace Avalonia_API.Extensions
|
||||
{
|
||||
var apiGroup = routeBuilder.MapGroup("/");
|
||||
|
||||
foreach (var endpoint in endpoints.Endpoints)
|
||||
foreach (var endpoint in endpoints.ForHost(EndpointHostTarget.Api))
|
||||
{
|
||||
var routeHandlerBuilder = MapEndpoint(apiGroup, endpoint, serviceProvider);
|
||||
|
||||
@@ -43,7 +44,14 @@ namespace Avalonia_API.Extensions
|
||||
// 鉴权(使用 ASP.NET Core 原生鉴权机制)
|
||||
if (endpoint.RequireAuthorization)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(endpoint.Policy))
|
||||
if (endpoint.Roles.Count > 0)
|
||||
{
|
||||
routeHandlerBuilder.RequireAuthorization(new AuthorizeAttribute
|
||||
{
|
||||
Roles = string.Join(',', endpoint.Roles),
|
||||
});
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(endpoint.Policy))
|
||||
{
|
||||
routeHandlerBuilder.RequireAuthorization(endpoint.Policy);
|
||||
}
|
||||
@@ -57,6 +65,31 @@ namespace Avalonia_API.Extensions
|
||||
{
|
||||
routeHandlerBuilder.WithName(endpoint.Name);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(endpoint.OpenApiTag))
|
||||
{
|
||||
routeHandlerBuilder.WithTags(endpoint.OpenApiTag);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(endpoint.OpenApiDescription))
|
||||
{
|
||||
routeHandlerBuilder.WithDescription(endpoint.OpenApiDescription);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(endpoint.OpenApiSummary))
|
||||
{
|
||||
routeHandlerBuilder.WithSummary(endpoint.OpenApiSummary);
|
||||
}
|
||||
|
||||
if (endpoint.OpenApiRequestType is not null)
|
||||
{
|
||||
routeHandlerBuilder.Accepts(endpoint.OpenApiRequestType, "application/json");
|
||||
}
|
||||
|
||||
if (endpoint.OpenApiResponseType is not null)
|
||||
{
|
||||
routeHandlerBuilder.Produces(200, endpoint.OpenApiResponseType, "application/json");
|
||||
}
|
||||
}
|
||||
|
||||
return routeBuilder;
|
||||
@@ -87,6 +120,7 @@ namespace Avalonia_API.Extensions
|
||||
{
|
||||
var ctx = await BuildContextFromHttpContext(httpContext);
|
||||
ctx.Items["ServiceProvider"] = serviceProvider;
|
||||
ctx.Items["User"] = httpContext.User;
|
||||
|
||||
var result = await unifiedHandler(ctx);
|
||||
|
||||
@@ -127,6 +161,7 @@ namespace Avalonia_API.Extensions
|
||||
}
|
||||
|
||||
ctx.Items["HttpContext"] = httpContext;
|
||||
ctx.Items["User"] = httpContext.User;
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
@@ -28,17 +28,21 @@ try
|
||||
// 初始化数据库(自动迁移 + 种子数据)
|
||||
app.Services.InitializeDatabase<AppDataContext>();
|
||||
|
||||
// 启动时打印所有接口
|
||||
var endpoints = app.Services.GetRequiredService<ServiceEndpointCollection>();
|
||||
EndpointPrinter.PrintEndpoints(endpoints, "Avalonia-API 接口列表");
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
app.UseSwaggerUI(options =>
|
||||
{
|
||||
options.SwaggerEndpoint("/openapi/v1.json", "Avalonia API v1");
|
||||
options.RoutePrefix = "swagger";
|
||||
});
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
// 将统一端点映射到 ASP.NET Core 路由
|
||||
|
||||
@@ -6,6 +6,13 @@
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Jwt": {
|
||||
"Issuer": "Avalonia-API",
|
||||
"Audience": "Avalonia-Client",
|
||||
"SigningKey": "change-this-development-signing-key-at-least-32-bytes",
|
||||
"AccessTokenMinutes": 60,
|
||||
"RefreshTokenDays": 30
|
||||
},
|
||||
"DatabaseConfiguration": {
|
||||
"Provider": "SQLite",
|
||||
"ConnectionString": "Data Source=avalonia-api.db",
|
||||
|
||||
Reference in New Issue
Block a user