C# .NET6 WebAPI JWT身份验证服务

自定义扩展类

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Text.Json;

namespace Demo
{
    /// <summary>
    /// 自定义扩展类
    /// </summary>
    public static class CustomExpand
    {
        /// <summary>
        /// 添加模型绑定异常处理
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="CustomException"></exception>
        public static void AddModelBindingExceptionHandling(this IServiceCollection services)
        {
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    // 获取验证失败的模型字段
                    //var errors = actionContext.ModelState
                    //    .Where(s => s.Value != null && s.Value.ValidationState == ModelValidationState.Invalid)
                    //    .SelectMany(s => s.Value!.Errors.ToList())
                    //    .Select(e => e.ErrorMessage)
                    //    .ToList();
                    var error = actionContext.ModelState
                        .Where(s => s.Value != null && s.Value.ValidationState == ModelValidationState.Invalid)
                        .SelectMany(s => s.Value!.Errors.ToList())
                        .Select(e => e.ErrorMessage).FirstOrDefault();
                    // 统一返回格式
                    throw new CustomException(ResultLevel.Error, ResultCode.ModelError, error);
                    //var result = new CustomResult<List<string>>(ResultLevel.Error, ResultCode.ModelError, errors);
                    //return new BadRequestObjectResult(result);
                };
            });
        }
        /// <summary>
        /// 添加身份认证事件
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public static JwtBearerOptions AddAuthenticationEvents(this JwtBearerOptions options)
        {
            // JWT
            options.Events = new JwtBearerEvents()
            {
                // 未登录
                OnChallenge = context => AuthenticationFailed(context),
                // 身份认证失败
                OnAuthenticationFailed = context => AuthenticationFailed(context),
                // 没有权限
                OnForbidden = context => AuthenticationFailed(context),
            };
            return options;
        }
        /// <summary>
        /// 身份认证失败
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private static Task AuthenticationFailed(BaseContext<JwtBearerOptions> context)
        {
            var ex = new CustomException(ResultLevel.Error, ResultCode.IdentityAuthFailed, ResultMsg.IdentityAuthFailed);
            var result = new CustomResult<CustomException>(ex);
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            context.Response.ContentType = "application/json";
            context.Response.Body.Flush();
            context.Response.Body.Position = 0;
            return JsonSerializer.SerializeAsync(context.Response.Body, result,
                new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }
            );
        }
    }
}
View Code

使用方法

// 添加JWT身份验证服务
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
    // Jwt验证配置
    .AddJwtBearer(options =>
    {
        // 身份认证参数
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = configuration["Jwt:Issuer"],
            ValidAudience = configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:IssuerSigningKey"]))
        };
        // 身份认证事件
        options.AddAuthenticationEvents();
    });

 

posted @ 2024-04-02 10:21  Mr_Xul  阅读(145)  评论(0编辑  收藏  举报