Class: Slosilo::JWT

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

Overview

Note:

This is not intended to be a general-purpose JWT implementation.

A JWT-formatted Slosilo token.

Defined Under Namespace

Classes: JSONHash

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(claims = {}) ⇒ JWT

Create a new unsigned token with the given claims.

Parameters:

  • claims (#to_h) (defaults to: {})

    claims to embed in this token.



9
10
11
# File 'lib/slosilo/jwt.rb', line 9

def initialize claims = {}
  @claims = JSONHash[claims]
end

Instance Attribute Details

#claimsObject

Returns the value of attribute claims.



55
56
57
# File 'lib/slosilo/jwt.rb', line 55

def claims
  @claims
end

#headerObject

Returns the value of attribute header.



55
56
57
# File 'lib/slosilo/jwt.rb', line 55

def header
  @header
end

#signatureObject

Returns the value of attribute signature.



55
56
57
# File 'lib/slosilo/jwt.rb', line 55

def signature
  @signature
end

Class Method Details

.parse_compact(raw) ⇒ Object

Parse a token in compact representation



14
15
16
# File 'lib/slosilo/jwt.rb', line 14

def self.parse_compact raw
  load *raw.split('.', 3).map(&Base64.method(:urlsafe_decode64))
end

.parse_json(raw) ⇒ Object

Note:

only single signature is currently supported.

Parse a token in JSON representation.



20
21
22
23
24
25
# File 'lib/slosilo/jwt.rb', line 20

def self.parse_json raw
  raw = JSON.load raw unless raw.respond_to? :to_h
  parts = raw.to_h.values_at(*%w(protected payload signature))
  fail ArgumentError, "input not a complete JWT" unless parts.all?
  load *parts.map(&Base64.method(:urlsafe_decode64))
end

Instance Method Details

#add_signature(header, &sign) ⇒ Object

Note:

currently only a single signature is handled;

Add a signature. the token will be frozen after this operation.



30
31
32
33
34
35
# File 'lib/slosilo/jwt.rb', line 30

def add_signature header, &sign
  @claims = canonicalize_claims.freeze
  @header = JSONHash[header].freeze
  @signature = sign[string_to_sign].freeze
  freeze
end

#string_to_signObject



37
38
39
# File 'lib/slosilo/jwt.rb', line 37

def string_to_sign
  [header, claims].map(&method(:encode)).join '.'
end

#to_json(*a) ⇒ Object

Returns the JSON serialization of this JWT.



42
43
44
45
46
47
48
# File 'lib/slosilo/jwt.rb', line 42

def to_json *a
  {
    protected: encode(header),
    payload: encode(claims),
    signature: encode(signature)
  }.to_json *a
end

#to_sObject

Returns the compact serialization of this JWT.



51
52
53
# File 'lib/slosilo/jwt.rb', line 51

def to_s
  [header, claims, signature].map(&method(:encode)).join('.')
end