首页 文章

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

提问于
浏览
12

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

});

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

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

2 回答

  • 17

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

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

    在自定义身份验证提供程序中

    • ,覆盖/实现 ValidateIdentity(...) 和/或 RequestToken(...) 以检查每个请求的传入令牌

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

    例:

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

    2)使用令牌处理程序

    例:

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

    我要说的最好的方法是编写自定义属性 . 您需要继承 AuthorizeAttribute class并覆盖 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();
    }
    

相关问题