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(); services.AddScoped(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); 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(JwtTokenErrorEventFunc), OnForbidden = new Func(JwtPermissionEventFunc) }; }); //redis配置 services.AddSingleton(ConnectionMultiplexer.Connect(configuration["Redis:ConnectionString"])); return services; } /// /// token无效事件处理函数 /// /// /// public async static Task JwtTokenErrorEventFunc(JwtBearerChallengeContext context) { context.Response.ContentType = "application/json"; var res = new ResponseBase( 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( code: 2006, message: "用户无权限进行该操作", data: null ); context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync(JsonConvert.SerializeObject(res)); } } }