我使用UseJwtBearerAuthentication這樣UseJwtBearerAuthentication令牌期滿返回HTTP 500
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中的診斷窗口我看到這兩種例外:
System.IdentityModel.Tokens.SecurityTokenExpiredException」在System.IdentityModel.Tokens.dll(「IDX10223:Lifetime validation failed。The token is expired。
and上下行
拋出異常: 'System.ArgumentNullException' 在Microsoft.AspNet.Authentication.dll( 「值不能爲空」)
會如何返回一個HTTP 401未授權?
此代碼是否回所有異常的401S?對不起,不太瞭解代碼。 – sunil
當然。您可以瀏覽IdentityModel存儲庫並列出JWT安全性令牌處理程序可能拋出的所有異常,而不是捕獲所有異常。 – Pinpoint
如果您只想捕獲「過期令牌」錯誤,請更新catch塊以僅攔截SecurityTokenExpiredException異常。 – Pinpoint