Class: Nonnative::JwtToken

Inherits:
Object
  • Object
show all
Defined in:
lib/nonnative/jwt_token.rb

Overview

Generates Ed25519 (EdDSA) JWT tokens for authenticating against services under test.

The key id is set in the JWT kid header, and the claims match the common iss/aud/sub/iat/nbf/exp/jti set expected by verifiers such as go-service.

Examples:

jwt = Nonnative::JwtToken.new(issuer: 'iss', key: 'key-1', private_key: 'config/ed25519.pem', expiration: 3600)
jwt.generate(aud: 'GET /v1/things', sub: 'user-1')

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(issuer:, key:, private_key:, expiration:) ⇒ JwtToken

Returns a new instance of JwtToken.

Parameters:

  • issuer (String)

    the iss claim

  • key (String)

    the key id set in the JWT kid header

  • private_key (String)

    path to a PKCS#8 Ed25519 private key PEM file

  • expiration (Integer)

    token lifetime in seconds (drives exp)



19
20
21
22
23
24
# File 'lib/nonnative/jwt_token.rb', line 19

def initialize(issuer:, key:, private_key:, expiration:)
  @issuer = issuer
  @key = key
  @ed25519 = Nonnative::Ed25519Key.new(private_key)
  @expiration = expiration
end

Instance Method Details

#generate(aud:, sub:) ⇒ String

Generates a signed EdDSA JWT.

Parameters:

  • aud (String)

    the aud claim (for example "GET /v1/things" or a gRPC full method)

  • sub (String)

    the sub claim

Returns:

  • (String)

    the signed JWT



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/nonnative/jwt_token.rb', line 31

def generate(aud:, sub:)
  now = Time.now.to_i
  payload = {
    iss: @issuer,
    aud: aud,
    sub: sub,
    iat: now,
    nbf: now,
    exp: now + @expiration,
    jti: SecureRandom.uuid
  }

  JWT.encode(payload, Ed25519::SigningKey.new(@ed25519.seed), 'EdDSA', { kid: @key })
end