I am attempting to write code to sign a JWT token using a private key from a certificate. I have been attempting to adapt this StackOverflow answer (which uses jose-jwt
) to use Microsoft.IdentityModel
instead.
Having retrieved a X509Certificate2
(called certificate
in the code below), the following code successfully generates a token. (The payload below is a non-empty Dictionary<string, object>
)
var privateKey = certificate.GetRSAPrivateKey();
var tokenString = Jose.JWT.Encode(payload, privateKey, Jose.JwsAlgorithm.RS256);
However, an attempted equivalent implementation using Microsoft's IdentityModel doesn't work:
var privateKey = certificate.GetRSAPrivateKey();
var securityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(privateKey);
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.RsaSha256);
var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
var token = handler.CreateJwtSecurityToken(signingCredentials: credentials);
var tokenString = handler.WriteToken(token);
This code errors on the CreateJwtSecurityToken
line with the error:
IDX10630: The 'Microsoft.IdentityModel.Tokens.RsaSecurityKey' for signing cannot be smaller than 'System.Int32' bits. KeySize: 'System.Int32'. Parameter name: key
Does anybody know what is causing this error, and what could be done to resolve this?