Class: Coinbase::Authenticator

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/coinbase/authenticator.rb

Overview

A class that builds JWTs for authenticating with the Coinbase Platform APIs.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Authenticator

Initializes the Authenticator.



13
14
15
16
# File 'lib/coinbase/authenticator.rb', line 13

def initialize(app)
  super(app)
  @app = app
end

Instance Method Details

#build_jwt(uri) ⇒ String

Builds the JWT for the given API endpoint URI. The JWT is signed with the API key’s private key.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/coinbase/authenticator.rb', line 32

def build_jwt(uri)
  header = {
    typ: 'JWT',
    kid: Coinbase.configuration.api_key_name,
    nonce: SecureRandom.hex(16)
  }

  claims = {
    sub: Coinbase.configuration.api_key_name,
    iss: 'cdp',
    aud: ['cdp_service'],
    nbf: Time.now.to_i,
    exp: Time.now.to_i + 60, # Expiration time: 1 minute from now.
    uris: [uri]
  }

  raise Coinbase::InvalidConfiguration, 'API key not configured' unless Coinbase.configured?

  private_key = OpenSSL::PKey.read(Coinbase.configuration.api_key_private_key)
  JWT.encode(claims, private_key, 'ES256', header)
end

#call(env) ⇒ Object

Processes the request by adding the JWT to the Authorization header.



20
21
22
23
24
25
26
27
# File 'lib/coinbase/authenticator.rb', line 20

def call(env)
  method = env.method.downcase.to_sym
  uri = env.url.to_s
  uri_without_protocol = URI(uri).host
  token = build_jwt("#{method.upcase} #{uri_without_protocol}#{env.url.path}")
  env.request_headers['Authorization'] = "Bearer #{token}"
  @app.call(env)
end