【发布时间】:2020-12-27 06:26:45
【问题描述】:
我正在使用这篇文章https://codingstill.com/2016/01/verify-jwt-token-signed-with-rs256-using-the-public-key/#comment-3232 中找到的这个很棒的方法来验证我的 Azure idToken,它是用 RS256 签名的。
我注意到 Azure AD 在一段时间内更改了公钥。通过阅读这篇文章,https://nicksnettravels.builttoroam.com/post-2017-01-24-verifying-azure-active-directory-jwt-tokens-aspx。因此,每次需要验证令牌时,我都使用HttpClient(c#)从下面的URL获取公钥。
https://login.microsoftonline.com/{TenantId}/discovery/v2.0/keys?appid={AppId}
我确实得到了公钥的结果,它是 x5c 密钥中的字符串数组。以下是我的代码:
public static string GetPublicKeyAsync(string kid)
{
using (var client = new HttpClient())
{
HttpResponseMessage response = client.GetAsync("https://login.microsoftonline.com/{TenantId}/discovery/v2.0/keys?appid={AppId}").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
// by calling .Result you are synchronously reading the result
string responseBody = responseContent.ReadAsStringAsync().Result;
JObject json = JObject.Parse(responseBody);
string c = json["keys"].ToString();
List<ADPublic> allPublicKeys = JsonConvert.DeserializeObject<List<ADPublic>>(json["keys"].ToString());
foreach (ADPublic key in allPublicKeys)
{
if (key.kid == kid)
{
string certificateString = key.x5c[0];
var certificate = new X509Certificate2(Convert.FromBase64String(certificateString));
string pkey = Convert.ToBase64String(certificate.PublicKey.EncodedKeyValue.RawData);
var x509SecurityKey = new X509SecurityKey(certificate)
{
KeyId = key.kid
};
return pkey;
}
}
}
return null;
}
}
当我将我的公钥传递给验证方法时。我总是在 (PublicKeyFactory.CreateKey(keyBytes) method ) 行出现错误:
下面的代码请参考我在本题开头提到的验证方法:
// call my get public key function...
string key = GetPublicKeyAsync(headerData["kid"].ToString());
var keyBytes = Convert.FromBase64String(key); // your key here
**AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);**
GetInstance 中的未知对象:Org.BouncyCastle.Asn1.DerInteger 参数名称:obj
我想我快到了,但错过了最后一部分,你能帮忙吗?非常感谢!
【问题讨论】:
-
另一方面,kid is a key identifier not an actual key x5c 是一个确实包含密钥的证书
标签: azure oauth-2.0 azure-active-directory