Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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<Claim>
{
new("jti", Guid.NewGuid().ToString()),
new(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()),
new(JwtClaimTypes.Subject, _clientId),
},
now,
Expand Down Expand Up @@ -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
Expand Down