15

OpenID Connect 发现文档通常包含一个jwks_uri属性。从返回的数据jwks_uri似乎至少有两种不同的形式。x5c一种形式包含称为和的字段x5t。这方面的一个示例如下所示:

{
    "keys": [
        {
            "kty": "RSA",
            "use": "sig",
            "kid": "C61F8F2524D080D0DB0A508747A94C2161DEDAC8",
            "x5t": "xh-PJSTQgNDbClCHR6lMIWHe2sg", <------ HERE
            "e": "AQAB",
            "n": "lueb...",
            "x5c": [
                "MIIC/..." <------ HERE
            ],
            "alg": "RS256"
        }
    ]
}

我看到的另一个版本省略了 x5c 和 x5t 属性,但包含eand n。这方面的一个例子是:

{
    "keys": [
        {
            "kty": "RSA",
            "alg": "RS256",
            "use": "sig",
            "kid": "cb11e2f233aee0329a5344570349cddb6b8ff252",
            "n": "sJ46h...", <------ HERE
            "e": "AQAB"      <------ HERE
        }
    ]
}

我正在使用 C# Microsoft.IdentityModel.Tokens.TokenValidationParameters,我正在尝试弄清楚如何提供该属性IssuerSigningKey。此类的示例用法是

new TokenValidationParameters
{
    ValidateAudience = true,
    ValidateIssuer = true,
    ...,
    IssuerSigningKey = new X509SecurityKey(???) or new JsonWebKey(???) //How to create this based on x5c/x5t and also how to create this based on e and n ?
}

鉴于这两种不同的 JWK 格式,我如何使用它们来提供 ,IssuerSigningKey以便TokenValidationParameter我可以验证访问令牌?

4

3 回答 3

14

这就是我最终的结果:

//Model the JSON Web Key Set
public class JsonWebKeySet
{
     [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "keys", Required = Required.Default)]
     public JsonWebKey[] Keys { get; set; }
}


//Model the JSON Web Key object
public class JsonWebKey
{
    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "kty", Required = Required.Default)]
    public string Kty { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "use", Required = Required.Default)]
    public string Use { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "kid", Required = Required.Default)]
    public string Kid { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "x5t", Required = Required.Default)]
    public string X5T { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "e", Required = Required.Default)]
    public string E { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "n", Required = Required.Default)]
    public string N { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "x5c", Required = Required.Default)]
    public string[] X5C { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "alg", Required = Required.Default)]
    public string Alg { get; set; }
}

jwks_uri我首先向 OpenID Connect 发现文档中提供的端点发出请求。该请求将相应地填充上述对象。然后我将JsonWebKeySet对象传递给创建一个ClaimsPrincipal

string idToken = "<the id_token that was returned from the Token endpoint>";
List<SecurityKey> keys = this.GetSecurityKeys(jsonWebKeySet);
var parameters = new TokenValidationParameters
                 {
                      ValidateAudience = true,
                      ValidAudience = tokenValidationParams.Audience,
                      ValidateIssuer = true,
                      ValidIssuer = tokenValidationParams.Issuer,
                      ValidateIssuerSigningKey = true,
                      IssuerSigningKeys = keys,
                      NameClaimType = NameClaimType,
                      RoleClaimType = RoleClaimType
                  };

 var handler = new JwtSecurityTokenHandler();
 handler.InboundClaimTypeMap.Clear();

 SecurityToken jwt;
 ClaimsPrincipal claimsPrincipal = handler.ValidateToken(idToken, parameters, out jwt);

 // validate nonce
 var nonceClaim = claimsPrincipal.FindFirst("nonce")?.Value ?? string.Empty;

 if (!string.Equals(nonceClaim, "<add nonce value here>", StringComparison.Ordinal))
 {
      throw new AuthException("An error occurred during the authentication process - invalid nonce parameter");
 }

 return claimsPrincipal;

GetSecurityKeys方法是这样实现的

private List<SecurityKey> GetSecurityKeys(JsonWebKeySet jsonWebKeySet)
{
      var keys = new List<SecurityKey>();

      foreach (var key in jsonWebKeySet.Keys)
      {
          if (key.Kty == OpenIdConnectConstants.Rsa)
          {
             if (key.X5C != null && key.X5C.Length > 0)
             {
                string certificateString = key.X5C[0];
                var certificate = new X509Certificate2(Convert.FromBase64String(certificateString));

                var x509SecurityKey = new X509SecurityKey(certificate)
                                      {
                                          KeyId = key.Kid
                                      };

                 keys.Add(x509SecurityKey);
              }
              else if (!string.IsNullOrWhiteSpace(key.E) && !string.IsNullOrWhiteSpace(key.N))
              {
                  byte[] exponent = Base64UrlUtility.Decode(key.E);
                  byte[] modulus = Base64UrlUtility.Decode(key.N);

                  var rsaParameters = new RSAParameters
                                      {
                                          Exponent = exponent,
                                          Modulus = modulus
                                      };

                  var rsaSecurityKey = new RsaSecurityKey(rsaParameters)
                                       {
                                           KeyId = key.Kid
                                       };

                  keys.Add(rsaSecurityKey);
              }
              else
              {
                  throw new PlatformAuthException("JWK data is missing in token validation");
              }
          }
          else
          {
              throw new NotImplementedException("Only RSA key type is implemented for token validation");
          }
      }

      return keys;
  }
于 2017-11-20T11:08:29.723 回答
9

RSA 公钥将始终至少包含成员kty(具有 value RSAneAQAB即几乎所有密钥的 65537 公共指数)。

其他成员是可选的,用于提供有关密钥的信息。通常,您会找到以下推荐的成员:

  • 它的 ID ( kid),
  • 如何使用它(签名或加密)
  • 它们是为什么算法设计的(RS256在你的例子中)。

当密钥来自 X.509 证书时,您通常会找到x5tx5t#256(分别为 sha1 和 sha256 证书指纹)。一些系统不能直接使用 JWK,并且提供了 PKCS#1 密钥(x5c成员)。

您可以使用 ( n, e) 对或x5c成员(如果提供)。这取决于您使用的库/第三方应用程序的功能。

于 2017-11-07T08:01:15.127 回答
4

一点更新 - Microsoft.IdentityModel.Tokens nuget包含JsonWebKey 和一个采用 jwk JSON 字符串的构造函数。

// JSON class
public class OpenIdConnectKeyCollection
{
    [JsonProperty("keys")]
    public ICollection<JToken> JsonWebKeys { get; set; }
}  
  
// map the keys using the JSON ctor
var jsonKeys = keysResp.JsonWebKeys;
var jwk = jsonKeys
    .Select(k => new JsonWebKey(k.ToString()))
    .ToList();
于 2020-09-07T14:22:33.713 回答