diff --git a/application-restricted-signed-jwt-tutorials/csharp/auth/JwtHandler.cs b/application-restricted-signed-jwt-tutorials/csharp/auth/JwtHandler.cs index 926aad2..d2f89a4 100644 --- a/application-restricted-signed-jwt-tutorials/csharp/auth/JwtHandler.cs +++ b/application-restricted-signed-jwt-tutorials/csharp/auth/JwtHandler.cs @@ -25,6 +25,10 @@ public JwtHandler(String keyOrPfx, string audience, string clientId, string kid) { _signingCredentials = FromPrivateKey(keyOrPfx, kid); } + else if (keyOrPfx.EndsWith(".pem")) + { + _signingCredentials = FromPemPrivateKey(keyOrPfx, kid); + } else { throw new Exception("Can not recognise the certificate/key extension"); @@ -33,13 +37,13 @@ public JwtHandler(String keyOrPfx, string audience, string clientId, string kid) public string GenerateJwt(int expInMinutes = 1) { - var now = DateTime.UtcNow; + var now = DateTime.UtcNow; var token = new JwtSecurityToken( _clientId, _audience, new List { - new("jti", Guid.NewGuid().ToString()), + new(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()), new(JwtClaimTypes.Subject, _clientId), }, now, @@ -67,10 +71,28 @@ private SigningCredentials FromPrivateKey(string privateKeyPath, string kid) privateKey = privateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", ""); privateKey = privateKey.Replace("-----END RSA PRIVATE KEY-----", ""); var keyBytes = Convert.FromBase64String(privateKey); - + var rsa = RSA.Create(); rsa.ImportRSAPrivateKey(keyBytes, out _); - + + var rsaSecurityKey = new RsaSecurityKey(rsa) + { + KeyId = kid + }; + + return new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha512) + { + CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false } + }; + } + + private SigningCredentials FromPemPrivateKey(string privteKeyPath, string kid) + { + var privateKey = File.ReadAllText(privteKeyPath); + var rsa = RSA.Create(); + + rsa.ImportFromPem(privateKey); + var rsaSecurityKey = new RsaSecurityKey(rsa) { KeyId = kid