Module: OTP::JWT::Token

Includes:
ActiveSupport::Configurable
Defined in:
lib/otp/jwt/token.rb

Overview

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

Class Method Summary collapse

Class Method Details

.decode(token, opts = nil) ⇒ Hash

Decodes a valid token into [Hash]

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

Parameters:

  • token (String)

    , token to be decoded.

  • opts (Hash) (defaults to: nil)

    , extra options to be used during verification.

Returns:

  • (Hash)

    upon success



50
51
52
53
54
55
56
57
58
59
# 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) ⇒ String

Generates a token based on a payload and optional overwritable claims

Parameters:

  • payload (Hash)

    , data to be encoded into the token.

  • claims (Hash)

    , extra claims to be encoded into the token.

Returns:

  • (String)

    , a JWT token



23
24
25
26
27
28
29
30
31
# 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) ⇒ Hash

Verifies and returns decoded token data upon success

Parameters:

  • token (String)

    , token to be decoded.

  • opts (Hash) (defaults to: nil)

    , extra options to be used during verification.

Returns:

  • (Hash)

    , JWT token payload



39
40
41
# 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