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

Ily*_*dik 5 authentication oauth jwt openid-connect asp.net-core

我在我的应用程序中添加了一个JWT中间件:

app.UseJwtBearerAuthentication(options => { options.AutomaticAuthenticate = true;} )
Run Code Online (Sandbox Code Playgroud)

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

PS这是我添加保护的方式:

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

    config.Filters.Add(new AuthorizeFilter(policy));
});
Run Code Online (Sandbox Code Playgroud)

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

[HttpGet]
[AllowAnonymous]
public string Get(int id)
{
}
Run Code Online (Sandbox Code Playgroud)

澄清:如果没有令牌,这将有效,但如果令牌无效(例如已过期),即使公共资源将无法访问,也会抛出500(由于某些内部错误导致401应该真的存在).

Kév*_*let 5

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

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

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

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

[Authorize(Policy = "API")]
[HttpGet("your-action")]
public IActionResult Action() {
    ...
}
Run Code Online (Sandbox Code Playgroud)