Dav*_*oss 9 c# rsa jwt .net-core
我们有几个测试生成 jwt 请求来调用服务器来检索令牌。我们有 6 个测试,使用相同的数据对相同的方法进行相同的调用。方法如下:'''
private static string GenerateSignedTokenRequest(
string privateKey,
string privateKeyPass,
string clientID,
string audience,
int lifetime)
{
var jti = Guid.NewGuid().ToString();
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Jti, jti),
new Claim(JwtRegisteredClaimNames.Sub, clientID),
};
var decodedKey = DecodeRsaPrivateKeyFromPem(
privateKey,
privateKeyPass);
var priDecKey = decodedKey.Private as RsaPrivateCrtKeyParameters;
var rsaParams = DotNetUtilities.ToRSAParameters(priDecKey);
using (var rsa = RSA.Create(rsaParams))
{
var token = new JwtSecurityToken(
clientID,
audience,
claims,
DateTime.Now.AddMinutes(-1),
DateTime.Now.AddSeconds(lifetime),
new SigningCredentials(
new RsaSecurityKey(rsa),
SecurityAlgorithms.RsaSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
Run Code Online (Sandbox Code Playgroud)
'''
在 WriteToken(token) 方法上运行的每个其他测试中,我们都会收到以下错误:{“无法访问已处置的对象。\r\n对象名称:'RSA'。”}
令人困惑的是每个奇数测试都可以很好地通过此代码,但每个偶数测试都会失败。但是当我单独重新运行每个测试时,它们都是绿色的。只有当我将它们全部运行在一起时,其他所有测试才会失败。
从 .Net Core 和测试框架从 3.1.0 迁移到 3.1.4 时会发生这种情况
小智 11
更新这个
new SigningCredentials(
new RsaSecurityKey(rsa),
SecurityAlgorithms.RsaSha256)
Run Code Online (Sandbox Code Playgroud)
到
new SigningCredentials(
new RsaSecurityKey(rsa),
SecurityAlgorithms.RsaSha256){
CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false }
}
Run Code Online (Sandbox Code Playgroud)
参考:https://vmsdurano.com/-net-core-3-1-signing-jwt-with-rsa/
因此,问题似乎是 Windows Azure Active Directory IdentityModel Extensions for .Net 的升级。似乎有一个缓存不受 RSA.Create() 方法周围使用的影响。通过删除使用,所有测试都是绿色的。
以下是一些帮助我诊断的链接: https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues ?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
和:
https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/1433