Skip to content

Commit 9cc6346

Browse files
authored
Update JwtHelper sample (#997)
1 parent ac694b9 commit 9cc6346

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

samples/Samples.Jwt/JwtHelper.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,14 +102,20 @@ private static (SecurityKey SecurityKey, string SecurityAlgorithm) CreateAsymmet
102102
// interpret the key as base64
103103
var keyBytes = Convert.FromBase64String(key);
104104
// create a ECDsa key pair and import the key
105-
using var ecdsa = ECDsa.Create();
105+
var ecdsa = ECDsa.Create(); // do not dispose the instance (it is used by the security key)
106106
if (isPrivateKey)
107107
ecdsa.ImportECPrivateKey(keyBytes, out int _);
108108
else
109109
ecdsa.ImportSubjectPublicKeyInfo(keyBytes, out _);
110110
var securityKey = new ECDsaSecurityKey(ecdsa);
111111
// return the key
112-
return (securityKey, SecurityAlgorithms.EcdsaSha256);
112+
return (securityKey, securityKey.KeySize switch
113+
{
114+
256 => SecurityAlgorithms.EcdsaSha256,
115+
384 => SecurityAlgorithms.EcdsaSha384,
116+
521 => SecurityAlgorithms.EcdsaSha512,
117+
_ => throw new InvalidOperationException("Invalid key size."),
118+
});
113119
}
114120

115121
/// <summary>
@@ -118,6 +124,7 @@ private static (SecurityKey SecurityKey, string SecurityAlgorithm) CreateAsymmet
118124
public static (string PublicKey, string PrivateKey) CreateNewAsymmetricKeyPair()
119125
{
120126
using var ecdsa = ECDsa.Create();
127+
ecdsa.GenerateKey(ECCurve.NamedCurves.nistP256);
121128
var privateKey = Convert.ToBase64String(ecdsa.ExportECPrivateKey());
122129
var publicKey = Convert.ToBase64String(ecdsa.ExportSubjectPublicKeyInfo());
123130
return (publicKey, privateKey);

samples/Samples.Jwt/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828

2929
// or: use an asymmetric security key with a new random key pair (typically would be pulled from application secrets)
3030
//var (_, privateKey) = JwtHelper.CreateNewAsymmetricKeyPair();
31-
//JwtHelper.Instance = new(privateKey, JwtKeyType.PrivateKey);
31+
//JwtHelper.Instance = new(privateKey, SecurityKeyType.PrivateKey);
3232

3333
// configure authentication for GET/POST requests via the 'Authorization' HTTP header;
3434
// will authenticate WebSocket requests as well, but browsers cannot set the

0 commit comments

Comments
 (0)