如何在Azure API管理策略表达式中使用RSA SHA256签名JWT ?



Azure API管理策略表达式中,我需要创建一个用私钥签名的JWT。

当我尝试使用RSACryptoServiceProvider-只是为了检查这个反馈是否已经得到解决-我在试图保存策略时得到这个错误:

Usage of type 'System.Security.Cryptography.RSACryptoServiceProvider' is not supported within expressions 

根据maxim-kim的提示,我尝试了RSA.Create()并从本教程

转换
var privateKey = "whatever";
RSA rsa = RSA.Create();
rsa.ImportRSAPrivateKey(privateKey, out _);
var signingCredentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256)
{
CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false }
};
var now = DateTime.Now;
var unixTimeSeconds = new DateTimeOffset(now).ToUnixTimeSeconds();
var jwt = new JwtSecurityToken(
audience: _settings.Audience,
issuer: _settings.Issuer,
claims: new Claim[] {
new Claim(JwtRegisteredClaimNames.Iat, unixTimeSeconds.ToString(), ClaimValueTypes.Integer64),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(nameof(claims.FirstName), claims.FirstName),
new Claim(nameof(claims.LastName), claims.LastName),
new Claim(nameof(claims.Email), claims.Email)
},
notBefore: now,
expires: now.AddMinutes(30),
signingCredentials: signingCredentials
);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
return new JwtResponse
{
Token = token,
ExpiresAt = unixTimeSeconds,
};

但是得到下一个错误:

'RSA' does not contain a definition for 'ImportRSAPrivateKey' and no extension method 'ImportRSAPrivateKey' accepting a first argument of type 'RSA' could be found (are you missing a using directive or an assembly reference?)

所以我的问题是:有没有一种方法可以在Azure API管理策略表达式中创建签名JWT ?

多亏了这篇文章和其他文章,我成功地签署了一个APIM策略。因此,我想分享这一点。

<set-variable name="signedPayload" value="@{
using (RSA rsa = context.Deployment.Certificates["thumbprint"].GetRSAPrivateKey())
{
long unixTimeStampInSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();
string header = "{"alg":"RS256","typ":"JWT"}"; 
string claimset = String.Format("{{ "scope": "https://www.googleapis.com/auth/devstorage.read_write", "aud": "https://oauth2.googleapis.com/token", "iss": "blahblah.gserviceaccount.com", "iat": {0}, "exp": {1} }}", unixTimeStampInSeconds, unixTimeStampInSeconds + 3599);
string payload = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(header)) + "." + System.Convert.ToBase64String(Encoding.UTF8.GetBytes(claimset));
byte[] signature = rsa.SignData(Encoding.UTF8.GetBytes(payload), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return System.Net.WebUtility.UrlEncode(payload + "." + System.Convert.ToBase64String(signature));
}
}" />

目前不支持基于动态解析私钥和公钥的RSA初始化。

如果RSA参数不是特定于请求的,您可以将x509证书上传到包含所需RSA参数的APIM,并在表达式中使用它:

using (var rsa = context.Deployment.Certificates["thumbprint"].GetRSAPrivateKey())
{ 
....
}

最新更新