繁体   English   中英

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

[英]How to apply custom validation to JWT token on each request for ASP.NET WebApi?

在使用承载令牌验证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) },,

});

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

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

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

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

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

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

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

例:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    // ... other properties here
    Provider = new MyCustomTokenAuthenticationProvider()
    // ... other properties here
});

2)使用令牌处理程序

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

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

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

例:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    // ... other properties here
    TokenHandler = new MyCustomTokenHandler()
    // ... other properties here
});

我要说的最好的方法是编写自定义属性。 您需要继承AuthorizeAttribute类并覆盖AuthorizeCore方法,在那里您可以添加自定义验证。

完成后,只需用它来装饰你的控制器或方法。

https://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute(v=vs.118).aspx

实施示例:

public class MyCustomAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // your validation here
    }
}

用法考试:

[MyCustom]
public ActionResult MyAction()
{
    return View();
}

在.Net Core上你可以将它添加到JwtBearerOptions

options.Events = new JwtBearerEvents
{
    OnTokenValidated = AdditionalValidation
};

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

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

    return Task.CompletedTask;
}

好消息是context将包括您需要的所有内容,JWT令牌, HttpContextClaimsPrincipal等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM