2017-05-08 71 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 
});