Class: Nucleus::Adapters::OAuth2AuthClient

Inherits:
AuthClient
  • Object
show all
Includes:
Logging
Defined in:
lib/nucleus/core/adapter_extensions/auth/o_auth2_auth_client.rb

Instance Attribute Summary

Attributes inherited from AuthClient

#verify_ssl

Instance Method Summary collapse

Methods included from Logging

configure_logger_for, #log, logger_for

Constructor Details

#initialize(auth_url, check_certificates = true) ⇒ OAuth2AuthClient

Create a new instance of an Nucleus::Adapters::OAuth2AuthClient, which uses the standardized OAuth2 authentication method. false if they are to be ignored (e.g. when using self-signed certificates in development environments)

Parameters:

  • check_certificates (Boolean) (defaults to: true)

    true if SSL certificates are to be validated,

  • auth_url (String)

    URL to the OAuth2 endpoint



10
11
12
13
# File 'lib/nucleus/core/adapter_extensions/auth/o_auth2_auth_client.rb', line 10

def initialize(auth_url, check_certificates = true)
  @auth_url = auth_url
  super(check_certificates)
end

Instance Method Details

#auth_headerObject



25
26
27
28
29
30
31
32
33
34
# File 'lib/nucleus/core/adapter_extensions/auth/o_auth2_auth_client.rb', line 25

def auth_header
  raise Errors::EndpointAuthenticationError, 'Authentication client was not authenticated yet' unless @access_token
  if expired?
    log.debug('OAuth2 access_token is expired, trigger refresh before returning auth_header')
    # token is expired, renew first
    refresh
  end
  # then return the authorization header
  header
end

#authenticate(username, password) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/nucleus/core/adapter_extensions/auth/o_auth2_auth_client.rb', line 15

def authenticate(username, password)
  return self if @access_token
  response = post(query: { grant_type: 'password', username: username, password: password })
  body = body(response)
  extract(body)
  # refresh token is not included in later updates
  @refresh_token = body[:refresh_token]
  self
end

#refreshObject



36
37
38
39
40
41
42
43
44
# File 'lib/nucleus/core/adapter_extensions/auth/o_auth2_auth_client.rb', line 36

def refresh
  if @refresh_token.nil?
    raise Errors::EndpointAuthenticationError, "Can't refresh token before initial authentication"
  end
  log.debug("Attempt to refresh the access_token with our refresh_token: '#{@refresh_token}'")
  response = post(query: { grant_type: 'refresh_token', refresh_token: @refresh_token })
  extract(body(response))
  self
end