fix 登录授权的问题
This commit is contained in:
@ -7,6 +7,7 @@ using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using QYZH.InteractiveMagazine.Infrastructure.Auth;
|
||||
using QYZH.InteractiveMagazine.Infrastructure.Middleware;
|
||||
using QYZH.InteractiveMagazine.Models.Settings;
|
||||
using System.Security.Claims;
|
||||
@ -16,34 +17,23 @@ using System.Text.Encodings.Web;
|
||||
namespace QYZH.InteractiveMagazine.Infrastructure.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// 统一服务注册扩展
|
||||
/// Infrastructure service registration extensions.
|
||||
/// </summary>
|
||||
public static class DependencyInjectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 注册基础设施服务
|
||||
/// Registers infrastructure services.
|
||||
/// </summary>
|
||||
/// <param name="services">服务集合</param>
|
||||
/// <param name="configuration">配置</param>
|
||||
/// <param name="environment">运行环境</param>
|
||||
public static void AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment? environment = null)
|
||||
{
|
||||
AddJwtAuthentication(services, configuration, environment);
|
||||
|
||||
services.AddTransient<GlobalExceptionMiddleware>();
|
||||
services.AddTransient<OperationLogMiddleware>();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配置JWT认证
|
||||
/// </summary>
|
||||
/// <param name="services">服务集合</param>
|
||||
/// <param name="configuration">配置</param>
|
||||
/// <param name="environment">运行环境</param>
|
||||
private static void AddJwtAuthentication(IServiceCollection services, IConfiguration configuration, IWebHostEnvironment? environment = null)
|
||||
{
|
||||
// 开发环境下跳过 JWT 验证
|
||||
if (environment?.IsDevelopment() == true)
|
||||
{
|
||||
services.AddAuthentication("NoAuth")
|
||||
@ -74,37 +64,56 @@ public static class DependencyInjectionExtensions
|
||||
{
|
||||
OnTokenValidated = async context =>
|
||||
{
|
||||
var currentToken = GetBearerToken(context);
|
||||
if (string.IsNullOrEmpty(currentToken))
|
||||
{
|
||||
context.Fail("Invalid token");
|
||||
return;
|
||||
}
|
||||
|
||||
var userId = context.Principal?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
{
|
||||
context.Fail("无效的 Token");
|
||||
context.Fail("Invalid token");
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查管理后台 Token
|
||||
var adminToken = await RedisHelper.GetAsync($"InteractiveMagazine:AdminAuth:Token:{userId}");
|
||||
if (!string.IsNullOrEmpty(adminToken))
|
||||
var adminToken = await RedisHelper.GetAsync(JwtHelper.BuildAdminTokenKey(userId));
|
||||
var wxUserId = context.Principal?.FindFirst(JwtHelper.WxUserIdClaimType)?.Value;
|
||||
if (string.IsNullOrEmpty(wxUserId) && !string.IsNullOrEmpty(adminToken))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查微信端 Token
|
||||
var wechatToken = await RedisHelper.GetAsync($"InteractiveMagazine:WeChatAuth:Token:{userId}");
|
||||
if (!string.IsNullOrEmpty(wechatToken))
|
||||
if (!string.IsNullOrEmpty(wxUserId))
|
||||
{
|
||||
return;
|
||||
var wechatToken = await RedisHelper.GetAsync(JwtHelper.BuildWeChatTokenKey(wxUserId, userId));
|
||||
if (wechatToken == currentToken)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Redis 中不存在任何 Token,认证失败
|
||||
context.Fail("Token 已失效,请重新登录");
|
||||
context.Fail("Token expired, please login again");
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private static string? GetBearerToken(TokenValidatedContext context)
|
||||
{
|
||||
var authHeader = context.HttpContext.Request.Headers.Authorization.FirstOrDefault();
|
||||
if (string.IsNullOrWhiteSpace(authHeader) || !authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return authHeader.Substring("Bearer ".Length).Trim();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开发环境免认证处理器
|
||||
/// Authentication handler used only in development.
|
||||
/// </summary>
|
||||
public class NoAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
@ -115,14 +124,13 @@ public class NoAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
// 开发环境下始终认证成功
|
||||
var claims = new[]
|
||||
{
|
||||
new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "DevUser"),
|
||||
new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier, "0")
|
||||
new Claim(ClaimTypes.Name, "DevUser"),
|
||||
new Claim(ClaimTypes.NameIdentifier, "0")
|
||||
};
|
||||
var identity = new System.Security.Claims.ClaimsIdentity(claims, Scheme.Name);
|
||||
var principal = new System.Security.Claims.ClaimsPrincipal(identity);
|
||||
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, Scheme.Name);
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
|
||||
Reference in New Issue
Block a user