.NET – How to generate JWT token using private key?
Generating JWT token using private key

What is JWT?

JSON Web Tokens (commonly known as JWT) is an open standard to pass data between client and server, and enables you to transmit data back and forth between the server and the consumers in a secure manner.

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 JSON Web Tokens 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 JSON Web Tokens 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);

Contact Zodinet now if your business is looking for professional digital solutions.
——–
Hotline: (+84)866.09.02.09
Office: 45 Street 39, Royal Van Phuc, Van Phuc City, Thu Duc

View similar blog