Module: Sophos::Authentication

Included in:
API
Defined in:
lib/sophos/authentication.rb

Overview

Note:

Ensure that client_id and client_secret are configured before calling authentication methods.

Handles authentication flow for accessing Sophos APIs and stores tokens in global configuration. This module manages OAuth2-based token generation and sets up the API connection with authorization headers.

Instance Method Summary collapse

Instance Method Details

#auth_token(_options = {}) ⇒ String Also known as: login

Authorizes with the Sophos portal and retrieves an access token. This method performs an OAuth2 client credentials flow, returning a valid token.

Examples:

Authenticate and retrieve a token:

api.auth_token

Parameters:

  • _options (Hash) (defaults to: {})

    (optional) Any additional options for the request.

Returns:

  • (String)

    Access token for the Sophos API.

Raises:



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/sophos/authentication.rb', line 26

def auth_token(_options = {})
  raise ConfigurationError, 'Client id and/or secret not configured' unless client_id && client_secret

  # POST request to obtain the OAuth2 token using client credentials
  response = connection.post("#{id_endpoint}/api/v2/oauth2/token") do |request|
    request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    request.body = URI.encode_www_form(api_access_token_params)
  end

  api_process_token(response.body)
  setup_connection

  # Returns the generated access token
  self.access_token
rescue Faraday::UnauthorizedError => e
  raise AuthenticationError, "Unauthorized; response #{e}"
end