I am trying to figure out how to create a JWT in C# that has custom headers and is signed with a private key. My current attempt is as follows and seems to work except I haven’t found a way to include custom headers in it as well.
string publicKey = File.ReadAllText(@"C:\Users\blah\Desktop\Keys\testpublickey.pem");
string privateKey = File.ReadAllText(@"C:\Users\blah\Desktop\Keys\testprivatekey.pem");
var random = new Random();
int num = random.Next(1000000, 500000000);
var exp = DateTime.Now.AddMinutes(10).Ticks;
var claims = new List<Claim>();
claims.Add(new Claim("iss", "919d1ebb-bf3d-4c03-8855-b72b376db9ad"));
claims.Add(new Claim("sub", "919d1ebb-bf3d-4c03-8855-b72b376db9ad"));
claims.Add(new Claim("aud", @"https://api.alt.www.blah.com/auth/oauth/v2/token"));
claims.Add(new Claim("exp", exp.ToString()));
claims.Add(new Claim("jti", num.ToString()));
var token = CreateToken(claims, privateKey);
and CreateToken:
private static string CreateToken(List<Claim> claims, string privateRsaKey)
{
RSAParameters rsaParams;
using (var tr = new StringReader(privateRsaKey))
{
var pemReader = new PemReader(tr);
var privateRsaParams = pemReader.ReadObject() as Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters;
rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams);
}
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.ImportParameters(rsaParams);
Dictionary<string, object> payload = claims.ToDictionary(k => k.Type, v => (object)v.Value);
return Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256);
}
}
How can I add custom headers to a JWT signed with a private key?
>Solution :
Looks like you can pass extra headers to the method Jose.JWT.Encode as an optional parameter: parameter of type IDictionary<string, object> named: extraHeaders
var extraHeaders = new Dictionary<string, object>
{
////Your custom headers
};
string result = Jose.JWT.Encode(
payload, rsa, Jose.JwsAlgorithm.RS256, extraHeaders: extraHeaders);
Reference: jose-jwt/JWT.cs