vs2022 搭建NET6 WebApi 接口项目《四》 配置Jwt获取登录令牌
作者:互联网
1、添加验证
#region 添加验证校验 builder.Services.AddAuthentication(o => { o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultChallengeScheme = nameof(ApiResponseHandler); o.DefaultForbidScheme = nameof(ApiResponseHandler); }).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidAudience = "TestApiAdmin", ValidIssuer = "TestApiAdmin", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppsettingHelper.Get("JwtSecurityKey"))), }; }).AddScheme<AuthenticationSchemeOptions, ApiResponseHandler>(nameof(ApiResponseHandler), o => { });
2、启用验证
app.UseAuthentication(); app.UseAuthorization();
3、ApiResponseHandler类代码
public class ApiResponseHandler : AuthenticationHandler<AuthenticationSchemeOptions> { public ApiResponseHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } protected override Task<AuthenticateResult> HandleAuthenticateAsync() { throw new NotImplementedException(); } protected override async Task HandleChallengeAsync(AuthenticationProperties properties) { Response.ContentType = "application/json"; Response.StatusCode = StatusCodes.Status401Unauthorized; await Response.WriteAsync(JsonConvert.SerializeObject((new ApiResponse(StatusCode.CODE401)).MessageModel)); } protected override async Task HandleForbiddenAsync(AuthenticationProperties properties) { Response.ContentType = "application/json"; Response.StatusCode = StatusCodes.Status403Forbidden; await Response.WriteAsync(JsonConvert.SerializeObject((new ApiResponse(StatusCode.CODE403)).MessageModel)); } }
public class ApiResponse { public int Status { get; set; } = 200; public string Value { get; set; } = ""; public string MessageModel { get; set; } = ""; //public MessageModel<string> MessageModel = new MessageModel<string>() { }; public ApiResponse(StatusCode apiCode, string msg = null) { switch (apiCode) { case StatusCode.CODE401: { Status = 401; Value = "很抱歉,您无权访问该接口,请确保已经登录!"; } break; case StatusCode.CODE403: { Status = 403; Value = "很抱歉,您的访问权限等级不够,联系管理员!"; } break; case StatusCode.CODE404: { Status = 404; Value = "资源不存在!"; } break; case StatusCode.CODE500: { Status = 500; Value = msg; } break; } //MessageModel = new MessageModel<string>() //{ // status = Status, // msg = Value, // success = apiCode != StatusCode.CODE200 //}; } } public enum StatusCode { CODE200, CODE401, CODE403, CODE404, CODE500 }
标签:WebApi,Status,Jwt,Response,MessageModel,vs2022,new,public,StatusCode 来源: https://www.cnblogs.com/wenghan/p/16120520.html