Class: JWT::Rack::Token

Inherits:
Object
  • Object
show all
Defined in:
lib/jwt/rack/token.rb

Overview

Token encoding and decoding

Constant Summary collapse

TOKEN_REGEX =

abc123.abc123.abc123 (w/ signature) abc123.abc123. (‘none’)

/\A([a-zA-Z0-9\-\_\~\+\\]+\.[a-zA-Z0-9\-\_\~\+\\]+\.[a-zA-Z0-9\-\_\~\+\\]*)\z/.freeze
DEFAULT_HEADERS =
{ typ: 'JWT' }.freeze

Class Method Summary collapse

Class Method Details

.decode(token, secret, verify, options = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/jwt/rack/token.rb', line 26

def self.decode(token, secret, verify, options = {})
  raise 'Invalid token format.'     unless valid_token_format?(token)
  raise 'Invalid secret type.'      unless secret_of_valid_type?(secret)
  raise 'Unsupported verify value.' unless verify_of_valid_type?(verify)

  options[:algorithm] = 'HS256'     if options[:algorithm].nil?
  raise 'Unsupported algorithm'     unless algorithm_supported?(options[:algorithm])

  # If using an unsigned 'none' algorithm token you *must* set the
  # `secret` to `nil` and `verify` to `false` or it won't work per
  # the ruby-jwt docs. Using 'none' is probably not recommended.
  if options[:algorithm] == 'none'
    ::JWT.decode(token, nil, false, options)
  else
    ::JWT.decode(token, secret, verify, options)
  end
end

.encode(payload, secret, alg = 'HS256') ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/jwt/rack/token.rb', line 12

def self.encode(payload, secret, alg = 'HS256')
  raise 'Invalid payload. Must be a Hash.' unless payload.is_a?(Hash)
  raise 'Invalid secret type.'             unless secret_of_valid_type?(secret)
  raise 'Unsupported algorithm'            unless algorithm_supported?(alg)

  # if using an unsigned token ('none' alg) you *must* set the `secret`
  # to `nil` in which case any user provided `secret` will be ignored.
  if alg == 'none'
    ::JWT.encode(payload, nil, alg, DEFAULT_HEADERS)
  else
    ::JWT.encode(payload, secret, alg, DEFAULT_HEADERS)
  end
end

.secret_of_valid_type?(secret) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
# File 'lib/jwt/rack/token.rb', line 44

def self.secret_of_valid_type?(secret)
  secret.nil? ||
    secret.is_a?(String) ||
    secret.is_a?(OpenSSL::PKey::RSA) ||
    secret.is_a?(OpenSSL::PKey::EC)  ||
    (defined?(RbNaCl) && secret.is_a?(RbNaCl::Signatures::Ed25519::SigningKey)) ||
    (defined?(RbNaCl) && secret.is_a?(RbNaCl::Signatures::Ed25519::VerifyKey))
end