如何仅在 ASP.NET 5(ASP.NET 核心)中为受保护的操作添加令牌验证

How to add token validation only for protected actions in ASP.NET 5 (ASP.NET Core)

我已将 JWT 中间件添加到我的应用程序中:

app.UseJwtBearerAuthentication(options => { options.AutomaticAuthenticate = true;} )

现在,如果我的令牌未通过验证(例如已过期),我仍然会收到生命周期验证未通过的错误消息。有没有办法让中间件只为受保护的资源验证令牌?如果没有,那么我应该如何以及在何处调用自己的中间件(将令牌读入 HttpContext.User)?

P.S 这是我添加保护的方式:

services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();

    config.Filters.Add(new AuthorizeFilter(policy));
});

这就是我允许 public 访问的方式:

[HttpGet]
[AllowAnonymous]
public string Get(int id)
{
}

澄清一下:没有令牌这将起作用,但如果令牌无效(例如过期)甚至 public 资源将无法访问并且将抛出 500(由于某些内部错误因为 401 真的应该在那里)。

首先,您需要通过在 JWT 承载选项中将 AutomaticAuthentication 设置为 false 来禁用自动身份验证。

为确保调用 JWT 承载中间件执行特定操作,您可以使用 AddAuthenticationSchemes 创建自己的授权策略:

public void ConfigureServices(IServiceCollection services) {
    services.AddAuthorization(options => {
        options.AddPolicy("API", policy => {
            policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
            policy.RequireAuthenticatedUser();
        });
    });
}

然后,使用 Authorize 属性装饰您的控制器操作:

[Authorize(Policy = "API")]
[HttpGet("your-action")]
public IActionResult Action() {
    ...
}