Class: Bollard::Token

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token, signing_secret) ⇒ Token

Returns a new instance of Token.



20
21
22
23
# File 'lib/bollard/token.rb', line 20

def initialize(token, signing_secret)
  @token = token
  @signing_secret = signing_secret
end

Class Method Details

.generate(payload, signing_secret, ttl: 600) ⇒ Object

Generate the token header for a given payload. The token becomes invalid after ‘ttl` seconds.

Returns a JWT with an iat, exp, and signature data



12
13
14
15
16
17
# File 'lib/bollard/token.rb', line 12

def self.generate(payload, signing_secret, ttl: 600)
  iat = Time.now.to_i
  signature = Signature.calculate_signature(payload)
  jwt_payload = { iat: iat, exp: iat + ttl, Signature::EXPECTED_ALGORITHM => signature }
  JWT.encode(jwt_payload, signing_secret, 'HS256')
end

Instance Method Details

#verify_payload(payload, tolerance: nil) ⇒ Object

Verifies the token header for a given payload.

Raises a SignatureVerificationError in the following cases:

  • the header does not match the expected format

  • no hash found with the expected algorithm

  • hash doesn’t match the expected hash

Returns true otherwise



34
35
36
37
38
39
40
# File 'lib/bollard/token.rb', line 34

def verify_payload(payload, tolerance: nil)
  token_data, header = decode_token(tolerance)
  signature = extract_signature(token_data)
  verify_data(signature, payload)

  true
end