如何在每个ASP.NET WebApi请求上对JWT令牌应用自定义验证?

Nat*_*tan 13 c# jwt asp.net-web-api

在使用承载令牌验证Web api呼叫时,是否可以为每个请求添加自定义验证?

我正在使用以下配置,应用程序已经正确验证了JWT令牌.

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
    AuthenticationType = "jwt",
    TokenEndpointPath = new PathString("/api/token"),
    AccessTokenFormat = new CustomJwtFormat(),
    Provider = new CustomOAuthProvider(),
});

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    AllowedAudiences = new[] { "all" },
    IssuerSecurityTokenProviders = new[] { new SymmetricKeyIssuerSecurityTokenProvider(Config.JWT_Issuer, Config.JWT_Key) },,

});
Run Code Online (Sandbox Code Playgroud)

现在,由于令牌设置为永不过期,我想为使用不记名令牌的每个请求添加一个额外的自定义验证步骤,因此我可以根据请求验证一些其他信息,并在需要时拒绝访问.

在每个请求中添加此验证的正确位置在哪里?

Bis*_*hoy 18

要添加其他逻辑以验证或验证传入令牌:

1)使用身份验证提供程序

  1. 编写自定义提供程序继承OAuthBearerAuthenticationProvider或实现IOAuthBearerAuthenticationProvider

  2. 在您的自定义身份验证提供程序中,覆盖/实现ValidateIdentity(...)和/或RequestToken(...)检查每个请求的传入令牌

  3. 通过将自定义提供程序分配给JwtBearerAuthenticationOptions.Provider属性来使用它

例:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    // ... other properties here
    Provider = new MyCustomTokenAuthenticationProvider()
    // ... other properties here
});
Run Code Online (Sandbox Code Playgroud)

2)使用令牌处理程序

  1. 编写继承自的自定义标记处理程序 JwtSecurityTokenHandler

  2. 覆盖您想要扩展的任何相关方法(有很多!)

  3. 通过将自定义令牌处理程序分配给JwtBearerAuthenticationOptions.TokenHandler属性来使用它

例:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    // ... other properties here
    TokenHandler = new MyCustomTokenHandler()
    // ... other properties here
});
Run Code Online (Sandbox Code Playgroud)

  • 未来的读者警告:“JwtBearerAppBuilderExtensions.UseJwtBearerAuthentication(IApplicationBuilder,JwtBearerOptions)”已过时:“请参阅https://go.microsoft.com/fwlink/?linkid=845470”https://github.com/aspnet/AspNetCore/issues/ 2007年 (2认同)

小智 5

在 .Net Core 上,您可以将其添加到JwtBearerOptions

options.Events = new JwtBearerEvents
{
    OnTokenValidated = AdditionalValidation
};
Run Code Online (Sandbox Code Playgroud)

您的验证功能可能如下所示:

private static Task AdditionalValidation(TokenValidatedContext context)
{
    if ( /* any validation */ ) 
    {
        context.Fail("Failed additional validation");
    }

    return Task.CompletedTask;
}
Run Code Online (Sandbox Code Playgroud)

好消息是,context将包括所有你需要的JWT令牌的HttpContext,对ClaimsPrincipal