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?
CodePudding user response:
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
CodePudding user response:
You can add custom data via adding claims. They will be added to the token.
claims.Add(new Claim("MyCustomClaimName", "MyCustomClaimValue"));
In this case this data will be moving to the server when you provide the token in your Authorization header for example. So it is not recommended to keep big data there.
If you just need to return some data to the client when he obtains the token - just add extra properties to the response model.
