如何对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)使用身份验证提供程序
-
写一个自定义提供程序,继承自
IOAuthBearerAuthenticationProvider
-
在您的自定义身份验证提供程序中,覆盖/实现
ValidateIdentity(...)
和/或RequestToken(...)
以检查每个请求的传入令牌 -
通过将您的自定义提供程序分配给
JwtSecurityTokenHandler
-
覆盖您要扩展的任何相关方法(有很多方法!)
-
Write a custom provider inherit from
OAuthBearerAuthenticationProvider
or implementIOAuthBearerAuthenticationProvider
in your custom authentication provider, override/implement
ValidateIdentity(...)
and/orRequestToken(...)
to check the incoming token with each requestUse 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
Write a custom token handler inherit from
JwtSecurityTokenHandler
override any relevant method you like to extend (there are many!)
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屋!