我正在制作使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!