問題描述
我正在制作使用 IdentityServer4 來保護多個服務的原型,但需要注意的是,這些服務可能不會被遷移(在可預見的將來)以使用 ASP.NET Core 的 OWIN 中間件慣用語.因此,我無法通過簡單地提供 IdentityServer 的知名 JWKS 端點等方式來利用許多中間件助手來自動驗證 JWT.
I am prototyping the use of IdentityServer4 to secure several services, with the caveat that those services will likely not be migrated (in the forseeable future) to use the OWIN middleware idiom of ASP.NET Core. Consequently, I can not leverage the many middleware helpers that automate the validation of a JWT by simply providing the well-known JWKS endpoint of IdentityServer, among other things.
如果我能重建這種行為就好了,我想利用微軟的 JwtSecurityTokenHandler
實現(如果可能).但是,我不知道如何利用 IdentityServer 的發現端點提供的 JsonWebKeySet
和 JsonWebKey
類型來提取密鑰并執行驗證.
It would be nice if I could reconstruct this behavior, and I'd like to leverage Microsoft's JwtSecurityTokenHandler
implementation if possible. However, I can not figure out how to utilize the JsonWebKeySet
and JsonWebKey
types provided via IdentityServer's discovery endpoint to extract keys and perform the validation.
JwtSecurityTokenHandler
使用 TokenValidationParameters
來驗證 JWT,這些參數需要一個或多個 SecurityKey
對象來執行驗證.
JwtSecurityTokenHandler
uses TokenValidationParameters
to validate a JWT, and those parameters require an instance of one or more SecurityKey
objects to perform the validation.
ClaimsPrincipal ValidateJwt(string token, IdentityModel.Client.DiscoveryResponse discovery)
{
JwtSecurityToken jwt = new JwtSecurityToken(token);
TokenValidationParameters validationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidateIssuer = true,
RequireSignedTokens = true,
ValidIssuer = "expected-issuer",
ValidAudience = "expected-audience",
IssuerSigningKeys = discovery.KeySet.Keys /* not quite */
};
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
SecurityToken validatedToken;
return handler.ValidateToken(jwt, validationParameters, out validatedToken);
}
如何執行從 JsonWebKeySet
到 IEnumerable
的必要轉換,以便進行驗證?是否有另一種方法(除了 OWIN 中間件)也可以使用上面的 DiscoveryResponse
數據?
How do I perform the necessary translation from JsonWebKeySet
to IEnumerable<SecurityKey>
so that the validation can occur? Is there another method (apart from OWIN middleware) that will also work using the DiscoveryResponse
data above?
(遺憾的是,System.IdentityModel.Tokens.Jwt
的文檔不是最新的.)
(Sadly, the documentation for System.IdentityModel.Tokens.Jwt
is not up to date.)
推薦答案
查看此示例:
https:///github.com/IdentityServer/IdentityServer4/blob/master/samples/Clients/old/MvcManual/Controllers/HomeController.cs#L148
它從 JWK 手動檢索密鑰并填充驗證參數.
It manually retrieves the key from the JWK and populates the validation parameters.
這篇關于如何使用 JwtSecurityTokenHandler 和 JWKS 端點驗證 JWT?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!