2017-05-08 30 views
0

我正在嘗試處理包含jwt的請求的認證失敗。ASP.Net核心JwtBearerAuthentication失敗重定向 - 我可以指定HTTP方法嗎?

app.UseJwtBearerAuthentication(new JwtBearerOptions 
{ 
    AutomaticAuthenticate = true, 
    TokenValidationParameters = tokenValidationParameters, 
    Events = new JwtBearerEvents 
    { 
     OnAuthenticationFailed = (context) => 
     { 
      context.HandleResponse(); 
      context.Response.Redirect($"/api/session/error?message={context.Exception.Message}"); 
      return Task.FromResult(0); 
     } 
    } 
}); 

重定向的目標(上面context.Response.Redirect())與[HttpGet]屬性定義如下:我爲了得到失敗原因/的StatusCode回客戶端我需要執行重定向,如在下面的OnAuthenticationFailed處理程序理解但由於原始請求(在這種情況下)是http PUT,所以永遠不會被擊中。達到這種方法,如果原來的請求是HTTP GET:

[AllowAnonymous] 
[HttpGet("Error")] 
public IActionResult AuthenticationError([FromQuery]string message) 
{ 
} 

我明白這是爲什麼發生了:context.Response.Redirect()方法只接受「位置」和重用原始請求的HTTP方法(在這種情況下,PUT )。

有沒有一種方法可以指定重定向的http方法?或者我誤解了認證失敗處理的重定向是如何工作的?

回答

0

最簡單的解決方案是讓asp.net核心處理它。因爲客戶會直接找回401。

和設置AutomaticChallenge = true

所以

app.UseJwtBearerAuthentication(new JwtBearerOptions 
{ 
    AutomaticAuthenticate = true, 
    AutomaticChallenge = true, 
    TokenValidationParameters = tokenValidationParameters 
});