2026-06-01 13:42:40 +08:00
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
|
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
using QYZH.InteractiveMagazine.Infrastructure.Middleware;
|
|
|
|
|
using QYZH.InteractiveMagazine.Models.Settings;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace QYZH.InteractiveMagazine.Infrastructure.Extensions;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 统一服务注册扩展
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static class DependencyInjectionExtensions
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 注册基础设施服务
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="services">服务集合</param>
|
|
|
|
|
/// <param name="configuration">配置</param>
|
|
|
|
|
public static void AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
|
|
|
|
|
{
|
|
|
|
|
AddJwtAuthentication(services, configuration);
|
|
|
|
|
|
|
|
|
|
services.AddTransient<GlobalExceptionMiddleware>();
|
|
|
|
|
services.AddTransient<OperationLogMiddleware>();
|
2026-06-01 17:59:23 +08:00
|
|
|
|
2026-06-01 13:42:40 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 配置JWT认证
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="services">服务集合</param>
|
|
|
|
|
/// <param name="configuration">配置</param>
|
|
|
|
|
private static void AddJwtAuthentication(IServiceCollection services, IConfiguration configuration)
|
|
|
|
|
{
|
|
|
|
|
var jwtSettings = configuration.GetSection("JwtSettings").Get<JwtSettings>()!;
|
|
|
|
|
|
|
|
|
|
services.AddSingleton(jwtSettings);
|
|
|
|
|
|
|
|
|
|
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
|
|
|
|
.AddJwtBearer(options =>
|
|
|
|
|
{
|
|
|
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
|
|
|
{
|
|
|
|
|
ValidateIssuer = true,
|
|
|
|
|
ValidIssuer = jwtSettings.Issuer,
|
|
|
|
|
ValidateAudience = true,
|
|
|
|
|
ValidAudience = jwtSettings.Audience,
|
|
|
|
|
ValidateIssuerSigningKey = true,
|
|
|
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey!)),
|
|
|
|
|
ValidateLifetime = true,
|
|
|
|
|
ClockSkew = TimeSpan.Zero
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|