Module: NinjaOne::Authentication

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

Overview

The ‘NinjaOne::Authentication` module handles the authentication flow for the NinjaOne API. It manages access tokens and stores them in the global configuration. This module provides methods to log in to the NinjaOne portal using client credentials.

Instance Method Summary collapse

Instance Method Details

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

Authenticates with the NinjaOne API and retrieves an access token.

This method performs a client credentials flow to authenticate with the NinjaOne API. The access token is stored in the global configuration for subsequent API calls.

Examples:

Authenticate and retrieve an access token:

token = NinjaOne::Authentication.auth_token

Parameters:

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

    Options for the authentication request (currently unused).

Returns:

  • (String)

    The access token for authenticated API requests.

Raises:

  • (ConfigurationError)

    If ‘client_id`, `client_secret` or `endpoint` are not configured.

  • (AuthenticationError)

    If the authentication fails due to invalid credentials or other issues.



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

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

  con = connection
  response = con.post('/ws/oauth/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)

  self.access_token
rescue Faraday::ForbiddenError, Faraday::BadRequestError, Faraday::ResourceNotFound => e
  raise AuthenticationError.new "Unauthorized; response #{e}"
end