Create and Sign a JSON Web Token (JWT) with C# and .Net

.Net comes with handy tools to deal with JWT Tokens. Just add the following Microsoft packages as dependencies of your .Net project: 

  • Microsoft.IdentityModel.Tokens
  • System.IdentityModel.Tokens.Jwt
using System;
using System.IO;
using System.Security.Cryptography;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
namespace AaaSDocumentation
{
    class SignToken
    {
        static void Main(string[] args)
        {
            try
            {
                // reading the content of a private key PEM file, PKCS8 encoded 
                string privateKeyPem = File.ReadAllText("...");
                // keeping only the payload of the key 
                privateKeyPem = privateKeyPem.Replace("-----BEGIN PRIVATE KEY-----", "");
                privateKeyPem = privateKeyPem.Replace("-----END PRIVATE KEY-----", "");
                byte[] privateKeyRaw = Convert.FromBase64String(privateKeyPem);
                // creating the RSA key 
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                provider.ImportPkcs8PrivateKey(new ReadOnlySpan<byte>(privateKeyRaw), out _);
                RsaSecurityKey rsaSecurityKey = new RsaSecurityKey(provider);
                // Generating the token 
                var now = DateTime.UtcNow;
                var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Sub, "YOUR_CLIENTID"),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };
                var handler = new JwtSecurityTokenHandler();
                var token = new JwtSecurityToken
                (
                    "YOUR_CLIENTID",
                    "https://AAAS_PLATFORM/idp/YOUR_TENANT/authn/token",
                    claims,
                    now.AddMilliseconds(-30),
                    now.AddMinutes(60),
                    new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
                );
                // handler.WriteToken(token) returns the token ready to send to AaaS !
                Console.WriteLine( handler.WriteToken(token) );
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine(
                     new System.Diagnostics.StackTrace().ToString()
                );
            }
        }
    }
}