ql_apimanager_backend/Apimanager_backend/Config/ServiceCollectionExtensions.cs

87 lines
3.8 KiB
C#

using Apimanager_backend.Dtos;
using Apimanager_backend.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using StackExchange.Redis;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
namespace Apimanager_backend.Config
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddAllService(this IServiceCollection services,IConfiguration configuration)
{
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddJWTService(configuration);
services.AddScoped<IUserService, UserService>();
services.AddScoped<IAuthService, AuthService>();
services.AddSingleton<ITokenService, TokenService>();
services.AddSingleton<IRefreshTokenService, RefreshTokenService>();
services.AddSingleton<IEmailService, EmailService>();
return services;
}
public static IServiceCollection AddJWTService(this IServiceCollection services,IConfiguration configuration)
{
var jwtSettings = configuration.GetSection("JwtSettings");
var key = Encoding.ASCII.GetBytes(jwtSettings["Secret"]);
// JWT配置
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//jwt参数
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSettings["Issuer"],
ValidAudience = jwtSettings["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
//添加自定义响应处理函数
options.Events = new JwtBearerEvents
{
OnChallenge = new Func<JwtBearerChallengeContext, Task>(JwtTokenErrorEventFunc),
OnForbidden = new Func<ForbiddenContext, Task>(JwtPermissionEventFunc)
};
});
//redis配置
services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(configuration["Redis:ConnectionString"]));
return services;
}
/// <summary>
/// token无效事件处理函数
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async static Task JwtTokenErrorEventFunc(JwtBearerChallengeContext context)
{
context.Response.ContentType = "application/json";
var res = new ResponseBase<object?>(
code: 1002,
message: "用户未登录或认证失败",
data: null
);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync(JsonConvert.SerializeObject(res));
context.HandleResponse();
}
public async static Task JwtPermissionEventFunc(ForbiddenContext context)
{
context.Response.ContentType = "application/json";
var res = new ResponseBase<object?>(
code: 2006,
message: "用户无权限进行该操作",
data: null
);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync(JsonConvert.SerializeObject(res));
}
}
}