如何对ASP.NET WebApi的每个请求将自定义验证应用于JWT令牌? [英] How to apply custom validation to JWT token on each request for ASP.NET WebApi?

查看:77
本文介绍了如何对ASP.NET WebApi的每个请求将自定义验证应用于JWT令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用承载令牌对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. 写一个自定义提供程序,继承自 IOAuthBearerAuthenticationProvider

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

  3. 通过将您的自定义提供程序分配给 JwtSecurityTokenHandler

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

  5. 通过将您的自定义令牌处理程序分配给

    Now, because tokens are set to never expire, I'd like to add an additional custom validation step to each request made with a bearer token, so I can validate some additional information per request and deny access if needed.

    Where is the right place to add this validation for each request?

    解决方案

    To add additional logic to authenticate or validate incoming tokens:

    1) Using an Authentication Provider

    1. Write a custom provider inherit from OAuthBearerAuthenticationProvider or implement IOAuthBearerAuthenticationProvider

    2. in your custom authentication provider, override/implement ValidateIdentity(...) and/or RequestToken(...) to check the incoming token with each request

    3. Use your custom provider by assigning it to the JwtBearerAuthenticationOptions.Provider property

    Example:

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


    2) Using A Token Handler

    1. Write a custom token handler inherit from JwtSecurityTokenHandler

    2. override any relevant method you like to extend (there are many!)

    3. Use your custom token handler by assigning it to the JwtBearerAuthenticationOptions.TokenHandler property

    Example:

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

    这篇关于如何对ASP.NET WebApi的每个请求将自定义验证应用于JWT令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆