【问题标题】:How do I validate a JWT using JwtSecurityTokenHandler and a JWKS endpoint?如何使用 JwtSecurityTokenHandler 和 JWKS 端点验证 JWT?
【发布时间】:2017-03-30 03:11:12
【问题描述】:

我正在设计使用 IdentityServer4 来保护多个服务的原型,但需要注意的是,这些服务可能不会被迁移(在可预见的将来)以使用 ASP.NET Core 的 OWIN 中间件惯用语。因此,我无法通过简单地提供 IdentityServer 的众所周知的 JWKS 端点来利用许多中间件助手来自动验证 JWT。

如果我能重建这种行为,那就太好了,如果可能的话,我想利用 Microsoft 的 JwtSecurityTokenHandler 实现。但是,我不知道如何利用 IdentityServer 的发现端点提供的 JsonWebKeySetJsonWebKey 类型来提取密钥并执行验证。

JwtSecurityTokenHandler 使用 TokenValidationParameters 验证 JWT,这些参数需要一个或多个 SecurityKey 对象的实例来执行验证。

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);
}

如何执行从JsonWebKeySetIEnumerable<SecurityKey> 的必要转换,以便进行验证?是否有另一种方法(除了 OWIN 中间件)也可以使用上面的 DiscoveryResponse 数据?

(遗憾的是,System.IdentityModel.Tokens.Jwt 的文档不是最新的。)

【问题讨论】:

    标签: asp.net oauth-2.0 jwt openid-connect identityserver4


    【解决方案1】:

    【讨论】:

    【解决方案2】:
    var jwks = "{ keys: [..." // your jwks json string
    var signingKeys = new JsonWebKeySet(jwks).GetSigningKeys();
    

    然后只需将其分配给您的TokenValidationParametersIssuerSigningKeys 属性。

    如果您是从 Web 服务读取 jwks,那么您需要一个 http 客户端首先读取它。

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 2021-10-15
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多