問題描述
是否可以在使用不記名令牌對 Web api 調(diào)用進行身份驗證時為每個請求添加自定義驗證?
Is it possible to add custom validation to each request when authenticating web api calls using a bearer token?
我正在使用以下配置,并且應(yīng)用程序已經(jīng)正確驗證了 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) },,
});
現(xiàn)在,由于令牌設(shè)置為永不過期,我想為每個使用不記名令牌發(fā)出的請求添加一個額外的自定義驗證步驟,這樣我就可以驗證每個請求的一些額外信息,并在需要時拒絕訪問.
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
或?qū)崿F(xiàn)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
覆蓋任何你想擴展的相關(guān)方法(有很多!)
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
});
這篇關(guān)于如何對 ASP.NET WebApi 的每個請求應(yīng)用自定義驗證到 JWT 令牌?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!