Class: Landline::Util::JWT

Inherits:
Object
  • Object
show all
Defined in:
lib/landline/util/jwt.rb

Overview

JSON Web Token construction class

Constant Summary collapse

ALGO =
{
  "HS256" => proc do |data, secret|
    Base64.urlsafe_encode64(
      OpenSSL::HMAC.digest("SHA256", secret, data)
    ).gsub('=', '')
  end,
  "HS384" => proc do |data, secret|
    Base64.urlsafe_encode64(
      OpenSSL::HMAC.digest("SHA384", secret, data)
    ).gsub('=', '')
  end,
  "HS512" => proc do |data, secret|
    Base64.urlsafe_encode64(
      OpenSSL::HMAC.digest("SHA512", secret, data)
    ).gsub('=', '')
  end
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, halgo = "HS256") ⇒ JWT

Create a new JWT token wrapper

Parameters:

  • data (Hash, Array)

    JSON-formattable data

  • halgo (String) (defaults to: "HS256")

    Name of the hash algorithm to use



38
39
40
41
42
43
44
45
# File 'lib/landline/util/jwt.rb', line 38

def initialize(data, halgo = "HS256")
  unless ALGO.include? halgo
    raise StandardError, "hash algorithm #{halgo} not supported"
  end

  @halgo = halgo
  @data = data
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



73
74
75
# File 'lib/landline/util/jwt.rb', line 73

def data
  @data
end

Class Method Details

.from_string(input, key) ⇒ JWT?

Construct an object from string

Parameters:

  • input (String)
  • key (String)

Returns:

  • (JWT, nil)

    returns nil if verification couldn’t complete



64
65
66
67
68
69
70
71
# File 'lib/landline/util/jwt.rb', line 64

def self.from_string(input, key)
  halgoj, dataj, sig = input.split(".")
  halgo = JSON.parse(Base64.urlsafe_decode64(halgoj))["alg"]
  return nil unless ALGO.include? halgo
  return nil if ALGO[halgo].call("#{halgoj}.#{dataj}", key) != sig

  new(JSON.parse(Base64.urlsafe_decode64(dataj)), halgo)
end

Instance Method Details

#make(key) ⇒ String

Construct a string representation of the current token

Parameters:

  • key (String)

Returns:

  • (String)


50
51
52
53
54
55
56
57
58
# File 'lib/landline/util/jwt.rb', line 50

def make(key)
  jsonheader = {
    "alg": @halgo,
    "typ": "JWT"
  }.to_json
  jsondata = @data.to_json
  data = "#{base64(jsonheader)}.#{base64(jsondata)}"
  "#{data}.#{ALGO[@halgo].call(data, key)}"
end