Back
Home » .NET – How to generate JWT token using private key?
.NET – How to generate JWT token using private key?

I’m using PemUtils package to read private key. You can find it here: PemUtils
We also need to install JWT package that com from Microsoft: JsonWebTokens

using PemUtils;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
string path = Directory.GetCurrentDirectory() + "/Credentials/private.key";
var handler = new JsonWebTokenHandler();
var now = DateTime.UtcNow;
RsaSecurityKey rsaKey;
using (var stream = new StringReader(path))
using (var reader = new PemReader(stream))
{
rsaKey = new RsaSecurityKey(reader.ReadRsaKey());
}
var signingCredentials = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSsaPssSha256);
var descriptor = new SecurityTokenDescriptor
{
Issuer = "Zodinet Admin",
Audience = "zodinet",
IssuedAt = now,
NotBefore = now,
Expires = now.AddHours(1),
Subject = new ClaimsIdentity(new List { new Claim("sub", "API Authenticator") }),
SigningCredentials = signingCredentials
};
string token = handler.CreateToken(descriptor);

BouncyCastle uses to read & parse private key from string. You can find it here: BouncyCastle
We also need to install JWT package that com from Microsoft: JsonWebTokens

using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
var handler = new JsonWebTokenHandler();
var now = DateTime.UtcNow;
string pem = //private key string;
PemReader pr = new PemReader(new StringReader(pem));
AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);
var rsaProvider = RSA.Create(2048); //It'll compatible with .NET Core v2.2
rsaProvider.ImportParameters(rsaParams);
var signingKey = new RsaSecurityKey(rsaProvider);
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSsaPssSha256);
var descriptor = new SecurityTokenDescriptor
{
Issuer = "Zodinet Admin",
Audience = "zodinet",
IssuedAt = now,
NotBefore = now,
Expires = now.AddHours(1),
Subject = new ClaimsIdentity(new List { new Claim("sub", "API Authenticator") }),
SigningCredentials = signingCredentials
};
string token = handler.CreateToken(descriptor);

View similar blog