Class: Nonnative::PasetoToken

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

Overview

Generates Ed25519 PASETO v4.public tokens for authenticating against services under test.

The key id is carried in a JSON footer ({"kid":"..."}), and the claims match the common iss/aud/sub/iat/nbf/exp/jti set expected by verifiers such as go-service. The signing library is required lazily so that requiring nonnative does not depend on rbnacl/libsodium being present.

Examples:

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

See Also:

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of PasetoToken.

Parameters:

  • issuer (String)

    the iss claim

  • key (String)

    the key id carried in the kid footer

  • private_key (String)

    path to a PKCS#8 Ed25519 private key PEM file

  • expiration (Integer)

    token lifetime in seconds (drives exp)



20
21
22
23
24
25
# File 'lib/nonnative/paseto_token.rb', line 20

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:, issued_at: nil, not_before: nil, expires_at: nil) ⇒ String

Generates a signed PASETO v4.public token.

Parameters:

  • aud (String)

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

  • sub (String)

    the sub claim

  • issued_at (Time, nil) (defaults to: nil)

    overrides the iat claim (default: now)

  • not_before (Time, nil) (defaults to: nil)

    overrides the nbf claim (default: issued_at)

  • expires_at (Time, nil) (defaults to: nil)

    overrides the exp claim (default: issued_at plus expiration)

Returns:

  • (String)

    the signed PASETO token



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/nonnative/paseto_token.rb', line 35

def generate(aud:, sub:, issued_at: nil, not_before: nil, expires_at: nil)
  load_dependencies!

  now = (issued_at || Time.now).utc
  claims = {
    'iss' => @issuer,
    'aud' => aud,
    'sub' => sub,
    'iat' => now.iso8601,
    'nbf' => (not_before || now).utc.iso8601,
    'exp' => (expires_at || (now + @expiration)).utc.iso8601,
    'jti' => SecureRandom.uuid
  }

  Paseto::V4::Public.new(@ed25519.pem).encode!(claims, footer: { 'kid' => @key }.to_json)
end