The purpose of this article is to create a JWT token secured with RSA256 private key.
The first step is to generate the private key used by the sending Application. To generate the key we need to use OpenSSL. If we are using Windows 10/11 OS, this is easy since the OpenSSL is already available at C:\Program Files\Git\usr\bin. If not available, it can be downloaded. The next step is to open Git Bash and start OpenSSL command. The next steps are mentioned below:
- openssl genrsa -out mbprivate.key 2048
Next we need to generate .csr file for submitting to Certificate Authority
- openssl req -new -key mbprivate.key -out mbrequest.csr
The .crt file that will be used by the application that will be needed by the receiving Application - openssl x509 -req -days 365 -in mbrequest.csr -signkey mbprivate.key -out mbcertificate.crt
If we need the JWT token to have a key id in the header we need to generate that:
- openssl rsa -in mbprivate.key -pubout -outform DER | openssl dgst -sha256 -binary | openssl enc -base64
[HttpGet]
public async Task<IActionResult> GenerateToken(string UserName)
{
var authClaims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var token = CreateRsaToken(authClaims);
return Ok(token);
}
private string CreateRsaToken(List<Claim> authClaims)
{
var rsaPrivateKey = System.IO.File.ReadAllText(System.IO.Path.Combine(Environment.CurrentDirectory, "mbprivate.key"));
using var rsa = RSA.Create();
rsa.ImportFromPem(rsaPrivateKey);
RsaSecurityKey rsaSecurityKey = new RsaSecurityKey(rsa);
rsaSecurityKey.KeyId = "gdNz9m5dR/tFD5AQ0SghAkiM8VAC2yWSkTb+K2Nv/k=";
var signingCredentials = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
{
CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false }
};
var now = DateTime.Now;
var jwt = new JwtSecurityToken(
issuer: _configuration["JWT:ValidIssuer"],
audience: _configuration["JWT:ValidAudience"],
claims: authClaims,
notBefore: now,
expires: now.AddHours(1),
signingCredentials: signingCredentials
);
return new JwtSecurityTokenHandler().WriteToken(jwt);
}