Module: GoldenTicket

Defined in:
lib/golden_ticket.rb,
lib/golden_ticket/version.rb

Overview

GoldenTicket Module

Constant Summary collapse

VERSION =

Version

'1.0.0'

Class Method Summary collapse

Class Method Details

.b64url_decode(s) ⇒ String

Decode Base64URL: Base64-decodes a String which has been encoded with #b64url_encode.

Parameters:

  • s (String)

    An encoded String

Returns:

  • (String)

    The decoded chunk



26
27
28
# File 'lib/golden_ticket.rb', line 26

def self.b64url_decode s
  Base64.urlsafe_decode64 s + ('=' * (((s.length % 4) > 0) ? (4 - (s.length % 4)) : 0))
end

.b64url_encode(s) ⇒ String

Encode Base64URL: Base64-encodes a String in way that plays nice with URLs (no special characters).

Parameters:

  • s (String)

    A chunk to encode

Returns:

  • (String)

    The encoded string



18
19
20
# File 'lib/golden_ticket.rb', line 18

def self.b64url_encode s
  Base64.urlsafe_encode64(s).gsub('=', '').gsub "\n", ''
end

.decode(key, token) ⇒ Object

Decode (Parse JWT): Splits up and decodes a given JSON Web Token, after having verified its authenticity.

Parameters:

  • key (String)

    Used for SHA-256 hashing

  • token (String)

    The token itself (duh…)

Returns:

  • (Object)

    The actual token information payload



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/golden_ticket.rb', line 56

def self.decode key, token

  # Split Token
  header_data, payload_data, secret_data = token.split '.'

  # Verify Token
  secret = "#{header_data}.#{payload_data}"
  raise 'Invalid Token' unless secret_data == b64url_encode(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), key, secret))

  # Pull dat Payload
  JSON.parse(b64url_decode(payload_data)).sym_keys
end

.encode(key, payload) ⇒ Object

Encode (Generate JWT): Produces a JSON Web Token (JWT) by SHA-256-hashing a payload’s JSON representation.

Parameters:

  • key (String)

    Used for SHA-256 hashing

  • payload (Object)

    The Actual token information payload



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/golden_ticket.rb', line 34

def self.encode key, payload

  # Prep Header - Always HMAC SHA 256 / JWT
  header = { alg: 'HS256', typ: 'JWT' }
  header_data = b64url_encode header.to_json

  # Prepare Payload
  payload_data = b64url_encode payload.to_json

  # Compute Token Secret
  secret = "#{header_data}.#{payload_data}"
  secret_data = b64url_encode OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), key, secret)

  # Generate Token
  "#{header_data}.#{payload_data}.#{secret_data}"
end