Contact Info
43 Street 3, Hiep Binh Chanh Ward
Thu Duc District, HCM City, Vietnam
[email protected]
+84 908 543479
Support

How should we call you?

    Follow Us

    Zodinet Technology Co.,Ltd

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

    Read Private Key From File

    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<Claim> { new Claim("sub", "API Authenticator") }),
    SigningCredentials = signingCredentials
    };
    
    string token = handler.CreateToken(descriptor);

    Read Private Key From Text String

    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<Claim> { new Claim("sub", "API Authenticator") }),
    SigningCredentials = signingCredentials
    };
    
    string token = handler.CreateToken(descriptor);