gpt4 book ai didi

asp.net-mvc - UseJwtBearerAuthentication 在 token 过期时返回 HTTP 500

转载 作者:行者123 更新时间:2023-12-01 17:23:04 28 4
gpt4 key购买 nike

我正在像这样使用 UseJwtBearerAuthentication

app.UseJwtBearerAuthentication(options =>
{
options.Authority = Configuration["Urls:IdentityServer"];
options.RequireHttpsMetadata = false;

options.Audience = Configuration["Urls:IdentityServer"] + "/resources";
options.AutomaticAuthenticate = true;
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
context.HandleResponse();
return Task.FromResult(0);
}
};
});

在 Visual Studio 的诊断窗口中,我看到以下 2 个异常:

System.IdentityModel.Tokens.SecurityTokenExpiredException' in System.IdentityModel.Tokens.dll ("IDX10223: Lifetime validation failed. The token is expired.

接下来

Exception thrown: 'System.ArgumentNullException' in Microsoft.AspNet.Authentication.dll ("Value cannot be null.")

如何返回 HTTP 401 Unauthorized?

最佳答案

这是一个 known bug 。可悲的是,the workaround you could use in beta8不再有效in RC1 .

您唯一的选择是编写一个捕获异常的中间件,以防止服务器返回 500 响应。当然,它很丑陋,并且可能会隐藏重要的异常,但它是唯一已知的适用于 RC1 的解决方法。

这是一个例子:

app.Use(next => async context =>
{
try
{
await next(context);
}

catch
{
// If the headers have already been sent, you can't replace the status code.
// In this case, re-throw the exception to close the connection.
if (context.Response.HasStarted)
{
throw;
}

// Rethrow the exception if it was not caused by IdentityModel.
if (!context.Items.ContainsKey("jwt-workaround"))
{
throw;
}

context.Response.StatusCode = 401;
}
});

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
RequireHttpsMetadata = false,

Audience = "http://localhost:54540/",
Authority = "http://localhost:54540/",

Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
context.HttpContext.Items["jwt-workaround"] = null;

return Task.FromResult(0);
}
};
});

关于asp.net-mvc - UseJwtBearerAuthentication 在 token 过期时返回 HTTP 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36629889/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com