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

Instance Method Details

#bearer_tokenObject



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

def bearer_token
  validate_keys!

  auth_token = JWT.encode(payload, client_key, 'ES256')

  "Bearer #{auth_token}"
end

#payloadObject



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

def payload
  {
    iat: Time.now.to_i + 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.



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/nomis/api/auth_token.rb', line 49

def validate_keys!
  client_pub = OpenSSL::PKey::EC.new client_key
  client_pub.private_key = nil
  client_pub_base64 = Base64.strict_encode64(client_pub.to_der)

  expected_client_pub = JWT.decode(client_token, nil, nil)[0]['key']

  unless client_pub_base64 == expected_client_pub
    raise 'Incorrect private key supplied ' \
          + '(does not match public key within token)'
  end
end