2016-04-14 38 views
3

我使用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未授權?

回答

5

這是一個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); 
     } 
    }; 
}); 
+0

此代碼是否回所有異常的401S?對不起,不太瞭解代碼。 – sunil

+0

當然。您可以瀏覽IdentityModel存儲庫並列出JWT安全性令牌處理程序可能拋出的所有異常,而不是捕獲所有異常。 – Pinpoint

+1

如果您只想捕獲「過期令牌」錯誤,請更新catch塊以僅攔截SecurityTokenExpiredException異常。 – Pinpoint

相關問題