module OTP::JWT::Token

A configurable set of token helpers to sign/verify an entity JWT token.

Public Class Methods

decode(token, opts = nil) { |verified| ... } click to toggle source

Decodes a valid token into [Hash]

Requires a block, yields JWT data. Will catch any JWT exception.

@param token [String], token to be decoded. @param opts [Hash], extra options to be used during verification. @return [Hash] upon success

# File lib/otp/jwt/token.rb, line 50
def self.decode(token, opts = nil)
  verified, _ = self.verify(token, opts)

  if block_given?
    yield verified
  else
    verified
  end
rescue ::JWT::EncodeError, ::JWT::DecodeError
end
sign(payload) click to toggle source

Generates a token based on a payload and optional overwritable claims

@param payload [Hash], data to be encoded into the token. @param claims [Hash], extra claims to be encoded into the token.

@return [String], a JWT token

# File lib/otp/jwt/token.rb, line 23
def self.sign(payload)
  payload = payload.dup.as_json

  if payload['exp'].blank? && self.jwt_lifetime.to_i > 0
    payload['exp'] = Time.now.to_i + self.jwt_lifetime
  end

  ::JWT.encode(payload, self.jwt_signature_key, self.jwt_algorithm)
end
verify(token, opts = nil) click to toggle source

Verifies and returns decoded token data upon success

@param token [String], token to be decoded. @param opts [Hash], extra options to be used during verification.

@return [Hash], JWT token payload

# File lib/otp/jwt/token.rb, line 39
def self.verify(token, opts = nil)
  ::JWT.decode(token.to_s, self.jwt_signature_key, true, opts || {})
end