Method: CF::UAA::TokenCoder.encode

Defined in:
lib/uaa/token_coder.rb

.encode(token_body, options = {}, obsolete1 = nil, obsolete2 = nil) ⇒ String

Constructs a signed JWT.

Parameters:

  • token_body

    Contents of the token in any object that can be converted to JSON.

  • options (Hash) (defaults to: {})

    Supported options:

    • :audience_ids [Array<String>, String] – An array or space separated string of values which indicate the token is intended for this service instance. It will be compared with tokens as they are decoded to ensure that the token was intended for this audience.

    • :skey [String] – used to sign and validate tokens using symmetrical key algoruthms

    • :pkey [String, File, OpenSSL::PKey::PKey] – may be a String or File in PEM or DER formats. May include public and/or private key data. The private key is used to sign tokens and the public key is used to validate tokens.

    • :algorithm [String] – Sets default used for encoding. May be HS256, HS384, HS512, RS256, RS384, RS512, or none.

    • :verify [String] – Verifies signatures when decoding tokens. Defaults to true.

    • :accept_algorithms [String, Array<String>] – An Array or space separated string of values which list what algorthms are accepted for token signatures. Defaults to all possible values of :algorithm except ‘none’.

Returns:

  • (String)

    a signed JWT token string in the form “xxxx.xxxxx.xxxx”.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/uaa/token_coder.rb', line 64

def self.encode(token_body, options = {}, obsolete1 = nil, obsolete2 = nil)
  unless options.is_a?(Hash) && obsolete1.nil? && obsolete2.nil?
    # deprecated: def self.encode(token_body, skey, pkey = nil, algo = 'HS256')
    warn "#{self.class}##{__method__} is deprecated with these parameters. Please use options hash."
    options = {:skey => options }
    options[:pkey], options[:algorithm] = obsolete1, obsolete2
  end
  options = normalize_options(options)
  algo = options[:algorithm]
  segments = [Util.json_encode64("typ" => "JWT", "alg" => algo)]
  segments << Util.json_encode64(token_body)
  if ["HS256", "HS384", "HS512"].include?(algo)
    sig = OpenSSL::HMAC.digest(init_digest(algo), options[:skey], segments.join('.'))
  elsif ["RS256", "RS384", "RS512"].include?(algo)
    sig = options[:pkey].sign(init_digest(algo), segments.join('.'))
  elsif algo == "none"
    sig = ""
  else
    raise SignatureNotSupported, "unsupported signing method"
  end
  segments << Util.encode64(sig)
  segments.join('.')
end