如何在ASP.NET WebApi的每个请求上对JWT令牌应用自定义validation?
在使用承载令牌validationWeb api呼叫时,是否可以为每个请求添加自定义validation?
我正在使用以下配置,应用程序已经正确validation了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) },, });
现在,由于令牌设置为永不过期,我想为使用不记名令牌的每个请求添加一个额外的自定义validation步骤,因此我可以根据请求validation一些其他信息,并在需要时拒绝访问。
在每个请求中添加此validation的正确位置在哪里?
要添加其他逻辑以validation或validation传入令牌:
1)使用身份validation提供程序
-
编写自定义提供程序inheritance自
OAuthBearerAuthenticationProvider
或实现IOAuthBearerAuthenticationProvider
-
在您的自定义身份validation提供程序中,覆盖/实现
ValidateIdentity(...)
和/或RequestToken(...)
以检查每个请求的传入令牌 -
通过将自定义提供程序分配给
JwtBearerAuthenticationOptions.Provider
属性来使用它
例:
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions { // ... other properties here Provider = new MyCustomTokenAuthenticationProvider() // ... other properties here });
2)使用令牌处理程序
-
编写从
JwtSecurityTokenHandler
inheritance的自定义标记处理程序 -
覆盖您想要扩展的任何相关方法(有很多!)
-
通过将自定义令牌处理程序分配给
JwtBearerAuthenticationOptions.TokenHandler
属性来使用它
例:
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions { // ... other properties here TokenHandler = new MyCustomTokenHandler() // ... other properties here });
我要说的最好的方法是编写自定义属性。 您需要inheritanceAuthorizeAttribute
类并覆盖AuthorizeCore
方法,在那里您可以添加自定义validation。
完成后,只需用它来装饰你的控制器或方法。
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(); }