Merge branch 'dev_add_auth_1029' into 'master'

Dev add auth 1029

See merge request ql/apismnagaer_backend!8
This commit is contained in:
2024-11-07 23:23:49 +08:00
committed by 南浔
34 changed files with 1547 additions and 191 deletions
@@ -9,6 +9,8 @@ namespace Apimanager_backend.Config
public MyAutomapper()
{
CreateMap<User,UserInfoDto>();
CreateMap<CreateUserDto, User>()
.ForMember(dest => dest.PassHash, opt => opt.MapFrom(src => src.Password));
}
}
}
@@ -1,6 +1,8 @@
using Apimanager_backend.Services;
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;
@@ -18,6 +20,7 @@ namespace Apimanager_backend.Config
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)
@@ -28,6 +31,7 @@ namespace Apimanager_backend.Config
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//jwt参数
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
@@ -38,11 +42,45 @@ namespace Apimanager_backend.Config
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));
}
}
}