问题描述
是否可以在使用不记名令牌对 Web api 调用进行身份验证时为每个请求添加自定义验证?
Is it possible to add custom validation to each request when authenticating web api calls using a bearer token?
我正在使用以下配置,并且应用程序已经正确验证了 JWT 令牌.
I'm using the following configuration and the application already validates the JWT tokens correctly.
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) },,
});
现在,由于令牌设置为永不过期,我想为每个使用不记名令牌发出的请求添加一个额外的自定义验证步骤,这样我就可以验证每个请求的一些额外信息,并在需要时拒绝访问.
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:
编写一个继承自
OAuthBearerAuthenticationProvider
或实现IOAuthBearerAuthenticationProvider
在您的自定义身份验证提供程序中,覆盖/实施 ValidateIdentity(...)
和/或 RequestToken(...)
以检查传入令牌每个请求
in your custom authentication provider, override/implement ValidateIdentity(...)
and/or RequestToken(...)
to check the incoming token with each request
通过将自定义提供程序分配给 JwtBearerAuthenticationOptions.Provider
属性
Use your custom provider by assigning it to the JwtBearerAuthenticationOptions.Provider
property
例子:
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
// ... other properties here
Provider = new MyCustomTokenAuthenticationProvider()
// ... other properties here
});
<小时>
2) 使用令牌处理程序
编写一个自定义令牌处理程序,继承自
JwtSecurityTokenHandler
覆盖任何你想扩展的相关方法(有很多!)
override any relevant method you like to extend (there are many!)
通过将自定义令牌处理程序分配给 JwtBearerAuthenticationOptions.TokenHandler
属性
Use your custom token handler by assigning it to the JwtBearerAuthenticationOptions.TokenHandler
property
例子:
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
// ... other properties here
TokenHandler = new MyCustomTokenHandler()
// ... other properties here
});
这篇关于如何对 ASP.NET WebApi 的每个请求应用自定义验证到 JWT 令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!