C# AuthenticationFailedContext.Success()在处理JWTBeareEvents.OnAuthenticationFailed时无效

C# AuthenticationFailedContext.Success()在处理JWTBeareEvents.OnAuthenticationFailed时无效,c#,authentication,asp.net-core,bearer-token,C#,Authentication,Asp.net Core,Bearer Token,我有一个ASP.NET核心Web API,目标是2.2,如果身份验证请求失败,我在处理该请求时遇到问题。身份验证请求需要传递有效的刷新令牌。我的代码在JWT过期时处理失败事件(我还提供了一个生存期验证器),然后在正确验证所提供的刷新令牌并因此使用时,发出一个新的JWT和刷新令牌。但是,不管我在上下文中调用Success(),管道都不会继续执行,而是返回403 以下是相关的Startup.cs部分: services.AddAuthentication(选项=> { options.Default

我有一个ASP.NET核心Web API,目标是2.2,如果身份验证请求失败,我在处理该请求时遇到问题。身份验证请求需要传递有效的刷新令牌。我的代码在JWT过期时处理失败事件(我还提供了一个生存期验证器),然后在正确验证所提供的刷新令牌并因此使用时,发出一个新的JWT和刷新令牌。但是,不管我在上下文中调用
Success()
,管道都不会继续执行,而是返回403

以下是相关的
Startup.cs
部分:

services.AddAuthentication(选项=>
{
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(选项=>
{
options.RequireHttpsMetadata=true;
options.SaveToken=true;
options.TokenValidationParameters=新的TokenValidationParameters
{
ValidateSuersigningKey=true,
IssuerSigningKey=new-SymmetricSecurityKey(Encoding.UTF8.GetBytes(配置[“身份验证:JwtSecret]”)),
validateisuer=false,
ValidateAudience=false,
ValidateLifetime=true,
LifetimeValidator=l10n.Api.Code.Auth.Bearer.JwtBearerExtensions.LifetimeValidator
};
options.Authority=Configuration[“Authentication:JwtAuthority”];
options.ClaimsIssuer=配置[“身份验证:JwtIssuer”];
options.Events=newjwtbearerevents();
options.Events.OnAuthenticationFailed=异步上下文=>wait context.AuthenticationFailed();
})
以及失败处理程序:

公共静态异步任务身份验证失败(此身份验证失败上下文)
{
ILoggerFactory loggerFactory=context.HttpContext.RequestServices.GetService();
ILogger logger=loggerFactory.CreateLogger(名称(JwtBearerExtensions));
字符串refreshToken=context.HttpContext.Request.Cookies[Defaults.RefreshTokenCookie];
if(string.IsNullOrEmpty(refreshToken))
{
logger.LogWarning(“没有为无效JWT提供刷新令牌,Cookies为{0}”,string.Join(“,”,context.HttpContext.Request.Cookies.Keys));
返回;
}
logger.LogInformation(“正在处理刷新令牌“{0}.”,refreshToken);
IConfiguration configuration=context.HttpContext.RequestServices.GetService();
IUserService userService=context.HttpContext.RequestServices.GetService();
ITokenHandler=context.HttpContext.RequestServices.GetService();
long?userId=wait handler.ValidateRefreshToken(refreshToken);
if(userId.HasValue)
{
User=await userService.GetUserAsync(userId.Value);
refreshToken=await handler.GenerateRefreshToken(userId.Value);
字符串jwtToken=BuildJwtToken(用户,配置);
context.HttpContext.Response.AddBeareAuthorization(jwtToken);
context.HttpContext.Response.AddRefreshTokenCookie(refreshToken);
context.Principal=newclaimsprincipal(BuildClaimsIdentity(user));
context.Success();
}
}
在Postman中检查403结果时,我可以在授权头中看到新的JWT,在cookie中看到新的刷新令牌。这些被正确地归因于
响应
对象。只是管道放弃了其余的处理,而我的控制器动作永远不会被调用


如何允许请求继续并完成,返回预期的JSON并发出(或刷新)新的身份验证会话?

解决方案是通过传入身份验证类型,为
claiminentity
使用正确的构造函数重载

对于对此解决方案感兴趣的人来说,403结果的出现是因为
app.UseAuthorization()
,其中一个策略由于身份验证问题而无法通过。在github发布的帖子中,专门构建的repo没有这个功能,而是生成了401