You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6 Web API JWT认证:如何自定义401状态码响应

实现ASP.NET Core 6 JWT认证自定义401响应

方法一:通过JWT认证事件自定义响应

这是和JWT认证绑定的最直接方案,重写认证流程中的OnChallenge事件来替换默认401响应:

  1. 先定义统一的响应模型:
public class ApiResponse
{
    public int ResultCode { get; set; }
    public string ResultMessage { get; set; } = string.Empty;
}
  1. 在Program.cs(旧模板用Startup.cs)的JWT认证配置中添加事件处理:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        // 保留你的JWT基础验证配置
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };

        // 自定义401响应逻辑
        options.Events = new JwtBearerEvents
        {
            OnChallenge = context =>
            {
                // 阻止框架生成默认响应
                context.HandleResponse();

                // 构建自定义响应
                var response = new ApiResponse
                {
                    ResultCode = 401,
                    ResultMessage = "Invalid token, please call Login() method."
                };

                // 设置响应头
                context.Response.StatusCode = 401;
                context.Response.ContentType = "application/json";

                // 序列化并写入响应
                return context.Response.WriteAsync(JsonSerializer.Serialize(response));
            }
        };
    });

方法二:全局状态码拦截中间件

如果需要统一处理所有场景下的401响应(包括非JWT认证触发的401),可以用自定义中间件:

  1. 创建中间件类:
public class CustomStatusCodeMiddleware
{
    private readonly RequestDelegate _next;

    public CustomStatusCodeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 先执行后续请求流程
        await _next(context);

        // 拦截未发送的401响应
        if (context.Response.StatusCode == StatusCodes.Status401Unauthorized && !context.Response.HasStarted)
        {
            context.Response.Clear();
            context.Response.ContentType = "application/json";

            var response = new ApiResponse
            {
                ResultCode = 401,
                ResultMessage = "Invalid token, please call Login() method."
            };

            await context.Response.WriteAsync(JsonSerializer.Serialize(response));
        }
    }
}
  1. 在Program.cs中注册中间件(需放在认证/授权中间件之后):
app.UseAuthentication();
app.UseAuthorization();

// 添加自定义状态码中间件
app.UseMiddleware<CustomStatusCodeMiddleware>();

注意事项

  • 若仅需针对JWT认证的401响应做定制,优先选方法一,避免影响其他场景的401逻辑。
  • 使用中间件时,需确保context.Response.HasStarted判断为false,避免在响应已发送后修改导致异常。

内容的提问来源于stack exchange,提问作者jancooth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:21:35