In my previous post of this series I showed how to generate key pair for EdDSA encryption algorithm. Let's now go further and use these keys to sign JWT token. If you remember from previous post "d" property of json object with keys pair belongs to private key. We will use this private key for signing our JWT token.
For creating JWT token we need to define claims. They are app/domain specific. We can add e.g. iss (issuer), exp (expired) and other standard claims (standard claims are defined in RFC 7519). Also we may add custom claims as we need in the app:
List<Claim> claims = ...; // fill claims
Then we need to load private key (from some secrets storage/vault usually):
var jwk = ...; // load private key
this jwk object may be json object showed in my previous post (plus it should have keyId string property for key identifier which may contain e.g. some guid).
Then we need to create EdDSA security key object and create signed token. We can do that using ScottBrady.IdentityModel nuget package (it uses Portable.BouncyCastle internally):
var edDsaSecurityKey = new EdDsaSecurityKey(new Ed25519PrivateKeyParameters(Base64UrlEncoder.DecodeBytes(jwk.d), 0)); edDsaSecurityKey.KeyId = jwk.keyId; var securityTokenHandler = new JwtSecurityTokenHandler(); string token = securityTokenHandler.WriteToken(securityTokenHandler.CreateToken(new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Issuer = ..., // define issuer (iss) claim as you need Expires = new DateTime(DateTime.UtcNow.AddMinutes(1)), // add expired date as you need SigningCredentials = new SigningCredentials(edDsaSecurityKey, "EdDSA") }));
This code will create JWT token signed with EdDSA private key. In the next post I will show how to verify this token using public EdDSA key.
Update 2024-01-09: see also Verify JWT tokens with EdDSA encryption algorithm.