Class: NOMIS::API::AuthToken

Inherits:
Object
  • Object
show all
Defined in:
lib/nomis/api/auth_token.rb

Overview

Encapsulates the complexity of generating a JWT bearer token

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ AuthToken

iat_fudge_factor allows you to correct for time drift between your client and the target server. For instance, if the server time is more than 10s in the future, it will reject any client-generated bearer tokens on the grounds of ‘iat skew too large’ (the timestamp in your payload is too old) In that case, you can pass an iat_fudge_factor of, say, 5, to generate a timestamp tagged 5s into the future and bring it back within the acceptable range.



19
20
21
22
23
24
25
26
27
# File 'lib/nomis/api/auth_token.rb', line 19

def initialize(params = {})
  self.client_key = OpenSSL::PKey::EC.new( params[:client_key] \
                      || default_client_key(params)
                    )
  self.client_token = params[:client_token] \
                    || default_client_token(params)

  self.iat_fudge_factor = default_iat_fudge_factor(params)
end

Instance Attribute Details

#client_keyObject

Returns the value of attribute client_key.



9
10
11
# File 'lib/nomis/api/auth_token.rb', line 9

def client_key
  @client_key
end

#client_tokenObject

Returns the value of attribute client_token.



9
10
11
# File 'lib/nomis/api/auth_token.rb', line 9

def client_token
  @client_token
end

#iat_fudge_factorObject

Returns the value of attribute iat_fudge_factor.



9
10
11
# File 'lib/nomis/api/auth_token.rb', line 9

def iat_fudge_factor
  @iat_fudge_factor
end

#nowObject

Returns the value of attribute now.



9
10
11
# File 'lib/nomis/api/auth_token.rb', line 9

def now
  @now
end

Instance Method Details

#bearer_tokenObject



29
30
31
32
33
# File 'lib/nomis/api/auth_token.rb', line 29

def bearer_token
  validate_keys!

  "Bearer #{auth_token}"
end

#payloadObject



35
36
37
38
39
40
# File 'lib/nomis/api/auth_token.rb', line 35

def payload
  {
    iat: current_timestamp + iat_fudge_factor,
    token: client_token
  }
end

#validate_keys!Object

Validate that the supplied private key matches the token’s public key. Obviously this step is optional, but when testing locally it’s easy to get one’s private keys in a muddle, and the API gateway’s error message can only say that the generated JWT token does not validate.



47
48
49
50
51
52
53
54
# File 'lib/nomis/api/auth_token.rb', line 47

def validate_keys!
  unless client_public_key_base64 == expected_client_public_key
    raise TokenMismatchError, 
          'Incorrect private key supplied ' \
          + '(does not match public key within token)',
          caller
  end
end