Module: Nexmo::JWT

Defined in:
lib/nexmo/jwt.rb

Class Method Summary collapse

Class Method Details

.generate(payload, private_key) ⇒ String

Generate an encoded JSON Web Token.

By default the Nexmo Ruby SDK generates a short lived JWT per request.

To generate a long lived JWT for multiple requests or to specify JWT claims directly call generate to generate a token, and set the token attribute on the client object.

Examples:

claims = {
  application_id: application_id,
  nbf: 1483315200,
  exp: 1514764800,
  iat: 1483228800
}

private_key = File.read('path/to/private.key')

client.token = Nexmo::JWT.generate(claims, private_key)

Parameters:

  • payload (Hash)
  • private_key (String, OpenSSL::PKey::RSA)

Returns:

  • (String)

33
34
35
36
37
38
39
40
41
# File 'lib/nexmo/jwt.rb', line 33

def self.generate(payload, private_key)
  payload[:iat] = iat = Time.now.to_i unless payload.key?(:iat) || payload.key?('iat')
  payload[:exp] = iat + 60 unless payload.key?(:exp) || payload.key?('exp')
  payload[:jti] = SecureRandom.uuid unless payload.key?(:jti) || payload.key?('jti')

  private_key = OpenSSL::PKey::RSA.new(private_key) unless private_key.respond_to?(:sign)

  ::JWT.encode(payload, private_key, 'RS256')
end