I want to generate a JWT Token in .Net 4.5 using an asymmetric key that I provide myself, but I am running into a few issues with the System.IdentityModel.Tokens.Jwt, version 4.0.3.
Preferably I would create my own 2048 keys, like provider allows me to do. The RSA.Create() constructor creates 1024 keys.
using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider(2048))
{
var publicPrivate = provider.ToXmlString(true);
var publicKeyOnly = provider.ToXmlString(false);
var stuff = provider.ExportParameters(true);
signingCredentials = new SigningCredentials(new RsaSecurityKey(RSA.Create()), SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); //no idea how to pull the key out of here.
}
In many examples one can drop RSAParameters into the RsaSecurityKey constructor, but now it only takes the RSA.Create() constructor (with optional string parameter) The following code snip comes from https://stackoverflow.com/a/38233644 Note that in this example the RSAParameters go nicely into the RsaSecurityKey constructor, which I cannot do with my version, I am restricted to using RSA.Create, it seams.
// NOTE: Replace this with your actual RSA public/private keypair!
var provider = new RSACryptoServiceProvider(2048);
var parameters = provider.ExportParameters(true);
// Build the credentials used to sign the JWT
var signingKey = new RsaSecurityKey(parameters); //not an option for me, unfortunately
Here is what I did. First I ran the debugger and the first time through I capture the XML from my new provider using the ToXmlString(Boolean) method of the new RSACryptoServiceProvider(2048). Then I made that an XML file for storage. (In this example I just use my hard drive for storage, obviously not production code.)
Now that I have the RSAPrameters, I have the key "that I provide myself", it could come from any secure storage - doesn't matter for this answer.
XmlDocument publicXmlParam = new XmlDocument();
publicXmlParam.Load("C:\\rsapublicprivate.xml");
// Here I "utilize my own 2048 keys"
RSACryptoServiceProvider provider = new RSACryptoServiceProvider(2048);
//This was the trick, we pass the RSA parameters as XML into the provider.
provider.FromXmlString(publicXmlParam.OuterXml);
// Then we use the provider in the constructor of the RsaSecurityKey
var key = new RsaSecurityKey(provider);
signingCredentials =
new SigningCredentials(
key,
SecurityAlgorithms.RsaSha256Signature,
SecurityAlgorithms.Sha256Digest);
Now I have the signing credentials that I need to sign my JWT Token.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With