Class: OAuth2::Client — Documentation by YARD 0.9.37

# Class: OAuth2::Client

Inherits:
  Object
  - Object
  - OAuth2::Client
  show all

Includes:
  FilteredAttributes

Defined in:
  lib/oauth2/client.rb

## Overview

The OAuth2::Client class

## Constant Summary collapse

RESERVED_REQ_KEYS =

rubocop:disable Metrics/ClassLength

      %w[body headers params redirect_count].freeze

RESERVED_PARAM_KEYS =

      (RESERVED_REQ_KEYS + %w[parse snaky snaky_hash_klass token_method]).freeze

## Instance Attribute Summary collapse

- #connection ⇒ Faraday::Connection

  The Faraday connection object.

- #id ⇒ Object readonly

  Returns the value of attribute id.

- #options ⇒ Object

  Returns the value of attribute options.

- #secret ⇒ Object readonly

  Returns the value of attribute secret.

- #site ⇒ Object

  Returns the value of attribute site.

## Instance Method Summary collapse

- #assertion ⇒ OAuth2::Strategy::Assertion

  The Assertion strategy.

- #auth_code ⇒ Object

  The Authorization Code strategy.

- #authorize_url(params = {}) ⇒ String

  The authorize endpoint URL of the OAuth2 provider.

- #client_credentials ⇒ Object

  The Client Credentials strategy.

- #get_token(params, access_token_opts = {}, extract_access_token = nil) {|opts| ... } ⇒ AccessToken?

  Retrieves an access token from the token endpoint using the specified parameters.

- #http_method ⇒ Symbol

  The HTTP Method of the request.

- #implicit ⇒ Object

  The Implicit strategy.

- #initialize(client_id, client_secret, options = {}) {|builder| ... } ⇒ Client constructor

  Initializes a new OAuth2::Client instance using the Client ID and Client Secret registered to your application.

- #password ⇒ Object

  The Resource Owner Password Credentials strategy.

- #redirection_params ⇒ Hash

  The redirect_uri parameters, if configured.

- #request(verb, url, req_opts = {}) {|req| ... } ⇒ OAuth2::Response

  Makes a request relative to the specified site root.

- #revoke_token(token, token_type_hint = nil, params = {}) {|req| ... } ⇒ OAuth2::Response

  Makes a request to revoke a token at the authorization server.

- #revoke_url(params = nil) ⇒ String

  The revoke endpoint URL of the OAuth2 provider.

- #token_url(params = nil) ⇒ String

  The token endpoint URL of the OAuth2 provider.

### Methods included from FilteredAttributes

included, #inspect

## Constructor Details

### #initialize(client_id, client_secret, options = {}) {|builder| ... } ⇒ `Client`

Initializes a new OAuth2::Client instance using the Client ID and Client Secret registered to your application.

Parameters:

- client_id (`String`) —

  the client_id value

- client_secret (`String`) —

  the client_secret value

- options (`Hash`) (defaults to: `{}`) —

  the options to configure the client

Options Hash (`options`):

- :site (`String`) —

  the OAuth2 provider site host

- :authorize_url (`String`) — default: `'/oauth/authorize'` —

  absolute or relative URL path to the Authorization endpoint

- :revoke_url (`String`) — default: `'/oauth/revoke'` —

  absolute or relative URL path to the Revoke endpoint

- :token_url (`String`) — default: `'/oauth/token'` —

  absolute or relative URL path to the Token endpoint

- :token_method (`Symbol`) — default: `:post` —

  HTTP method to use to request token (:get, :post, :post_with_query_string)

- :auth_scheme (`Symbol`) — default: `:basic_auth` —

  the authentication scheme (:basic_auth, :request_body, :tls_client_auth, :private_key_jwt)

- :connection_opts (`Hash`) — default: `{}` —

  Hash of connection options to pass to initialize Faraday

- :raise_errors (`Boolean`) — default: `true` —

  whether to raise an OAuth2::Error on responses with 400+ status codes

- :max_redirects (`Integer`) — default: `5` —

  maximum number of redirects to follow

- :logger (`Logger`) — default: `::Logger.new($stdout)` —

  Logger instance for HTTP request/response output; requires OAUTH_DEBUG to be true

- :access_token_class (`Class`) — default: `AccessToken` —

  class to use for access tokens; you can subclass OAuth2::AccessToken, @version 2.0+

- :ssl (`Hash`) —

  SSL options for Faraday

Yields:

- (`builder`) —

  The Faraday connection builder

    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    # File 'lib/oauth2/client.rb', line 50

    def initialize(client_id, client_secret, options = {}, &block)
      opts = options.dup
      @id = client_id
      @secret = client_secret
      @site = opts.delete(:site)
      ssl = opts.delete(:ssl)
      warn("OAuth2::Client#initialize argument `extract_access_token` will be removed in oauth2 v3. Refactor to use `access_token_class`.") if opts[:extract_access_token]
      @options = {
        authorize_url: "oauth/authorize",
        revoke_url: "oauth/revoke",
        token_url: "oauth/token",
        token_method: :post,
        auth_scheme: :basic_auth,
        connection_opts: {},
        connection_build: block,
        max_redirects: 5,
        raise_errors: true,
        logger: ::Logger.new($stdout),
        access_token_class: AccessToken,
      }.merge(opts)
      @options[:connection_opts][:ssl] = ssl if ssl
    end

## Instance Attribute Details

### #connection ⇒ `Faraday::Connection`

The Faraday connection object

Returns:

- (`Faraday::Connection`) —

  the initialized Faraday connection

    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    # File 'lib/oauth2/client.rb', line 85

    def connection
      @connection ||=
        Faraday.new(site, options[:connection_opts]) do |builder|
          oauth_debug_logging(builder)
          if options[:connection_build]
            options[:connection_build].call(builder)
          else
            builder.request(:url_encoded)             # form-encode POST params
            builder.adapter(Faraday.default_adapter)  # make requests with Net::HTTP
          end
        end
    end

### #id ⇒ `Object` (readonly)

Returns the value of attribute id.

    26
    27
    28
    # File 'lib/oauth2/client.rb', line 26

    def id
      @id
    end

### #options ⇒ `Object`

Returns the value of attribute options.

    27
    28
    29
    # File 'lib/oauth2/client.rb', line 27

    def options
      @options
    end

### #secret ⇒ `Object` (readonly)

Returns the value of attribute secret.

    26
    27
    28
    # File 'lib/oauth2/client.rb', line 26

    def secret
      @secret
    end

### #site ⇒ `Object`

Returns the value of attribute site.

    26
    27
    28
    # File 'lib/oauth2/client.rb', line 26

    def site
      @site
    end

## Instance Method Details

### #assertion ⇒ `OAuth2::Strategy::Assertion`

The Assertion strategy

This allows for assertion-based authentication where an identity provider
asserts the identity of the user or client application seeking access.

Returns:

- (`OAuth2::Strategy::Assertion`) —

  the initialized Assertion strategy

See Also:

- http://datatracker.ietf.org/doc/html/rfc7521
- http://datatracker.ietf.org/doc/html/draft-ietf-oauth-assertions-01#section-4.1

    314
    315
    316
    # File 'lib/oauth2/client.rb', line 314

    def assertion
      @assertion ||= OAuth2::Strategy::Assertion.new(self)
    end

### #auth_code ⇒ `Object`

The Authorization Code strategy

See Also:

- http://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-15#section-4.1

    280
    281
    282
    # File 'lib/oauth2/client.rb', line 280

    def auth_code
      @auth_code ||= OAuth2::Strategy::AuthCode.new(self)
    end

### #authorize_url(params = {}) ⇒ `String`

The authorize endpoint URL of the OAuth2 provider

Parameters:

- params (`Hash`) (defaults to: `{}`) —

  additional query parameters

Returns:

- (`String`) —

  the constructed authorize URL

    102
    103
    104
    105
    # File 'lib/oauth2/client.rb', line 102

    def authorize_url(params = {})
      params = (params || {}).merge(redirection_params)
      connection.build_url(options[:authorize_url], params).to_s
    end

### #client_credentials ⇒ `Object`

The Client Credentials strategy

See Also:

- http://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-15#section-4.4

    301
    302
    303
    # File 'lib/oauth2/client.rb', line 301

    def client_credentials
      @client_credentials ||= OAuth2::Strategy::ClientCredentials.new(self)
    end

### #get_token(params, access_token_opts = {}, extract_access_token = nil) {|opts| ... } ⇒ `AccessToken`?

Note:

The extract_access_token parameter is deprecated and will be removed in oauth2 v3.
Use access_token_class on initialization instead.

Retrieves an access token from the token endpoint using the specified parameters

#### Examples:

    client.get_token(
      'grant_type' => 'authorization_code',
      'code' => 'auth_code_value',
      'headers' => {'Authorization' => 'Basic ...'}
    )

Parameters:

- params (`Hash`) —

  a Hash of params for the token endpoint

  - params can include a ‘headers’ key with a Hash of request headers
  - params can include a ‘parse’ key with the Symbol name of response parsing strategy (default: :automatic)
  - params can include a ‘snaky’ key to control snake_case conversion (default: false)
- access_token_opts (`Hash`) (defaults to: `{}`) —

  options that will be passed to the AccessToken initialization

- extract_access_token (`Proc`) (defaults to: `nil`) —

  (deprecated) a proc that can extract the access token from the response

Yields:

- (`opts`) —

  The block is passed the options being used to make the request

Yield Parameters:

- opts (`Hash`) —

  options being passed to the http library

Returns:

- (`AccessToken`, `nil`) —

  the initialized AccessToken instance, or nil if token extraction fails
  and raise_errors is false

    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    # File 'lib/oauth2/client.rb', line 208

    def get_token(params, access_token_opts = {}, extract_access_token = nil, &block)
      warn("OAuth2::Client#get_token argument `extract_access_token` will be removed in oauth2 v3. Refactor to use `access_token_class` on #initialize.") if extract_access_token
      extract_access_token ||= options[:extract_access_token]
      req_opts = params_to_req_opts(params)
      response = request(http_method, token_url, req_opts, &block)

      # In v1.4.x, the deprecated extract_access_token option retrieves the token from the response.
      # We preserve this behavior here, but a custom access_token_class that implements #from_hash
      # should be used instead.
      if extract_access_token
        parse_response_legacy(response, access_token_opts, extract_access_token)
      else
        parse_response(response, access_token_opts)
      end
    end

### #http_method ⇒ `Symbol`

The HTTP Method of the request

Returns:

- (`Symbol`) —

  HTTP verb, one of [:get, :post, :put, :delete]

    270
    271
    272
    273
    274
    275
    # File 'lib/oauth2/client.rb', line 270

    def http_method
      http_meth = options[:token_method].to_sym
      return :post if http_meth == :post_with_query_string

      http_meth
    end

### #implicit ⇒ `Object`

The Implicit strategy

See Also:

- http://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-26#section-4.2

    287
    288
    289
    # File 'lib/oauth2/client.rb', line 287

    def implicit
      @implicit ||= OAuth2::Strategy::Implicit.new(self)
    end

### #password ⇒ `Object`

The Resource Owner Password Credentials strategy

See Also:

- http://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-15#section-4.3

    294
    295
    296
    # File 'lib/oauth2/client.rb', line 294

    def password
      @password ||= OAuth2::Strategy::Password.new(self)
    end

### #redirection_params ⇒ `Hash`

The redirect_uri parameters, if configured

The redirect_uri query parameter is OPTIONAL (though encouraged) when
requesting authorization. If it is provided at authorization time it MUST
also be provided with the token exchange request.

OAuth 2.1 note: Authorization Servers must compare redirect URIs using exact string matching.
This client simply forwards the configured redirect_uri; the exact-match validation happens server-side.

Providing :redirect_uri to the OAuth2::Client instantiation will take
care of managing this.

Returns:

- (`Hash`) —

  the params to add to a request or URL

See Also:

- https://datatracker.ietf.org/doc/html/rfc6749#section-4.1
- https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
- https://datatracker.ietf.org/doc/html/rfc6749#section-4.2.1
- https://datatracker.ietf.org/doc/html/rfc6749#section-10.6
- https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13

    339
    340
    341
    342
    343
    344
    345
    # File 'lib/oauth2/client.rb', line 339

    def redirection_params
      if opt