UseJwtBearerAuthentication在令牌到期时返回HTTP 500

sun*_*nil 3 asp.net-mvc jwt identityserver3 asp.net-core

我正在使用像这样的UseJwtBearerAuthentication

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);
        }
   }; 
});
Run Code Online (Sandbox Code Playgroud)

在visual studio的诊断窗口中,我看到以下两个例外:

System.IdentityModel.Tokens.dll中的System.IdentityModel.Tokens.SecurityTokenExpiredException'("IDX10223:生命周期验证失败.令牌已过期.

并下线

抛出异常:Microsoft.AspNet.Authentication.dll中的"System.ArgumentNullException"("值不能为空.")

如何返回HTTP 401 Unauthorized?

Kév*_*let 5

这是一个已知的错误.遗憾的是,您可以在beta8中使用的解决方法不再适用于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);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)