Class: OAuth2::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/oauth2/client.rb

Overview

The OAuth2::Client class

Constant Summary collapse

RESERVED_PARAM_KEYS =

rubocop:disable Metrics/ClassLength

%w[headers parse].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Instantiate a new OAuth 2.0 client 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 create the client with

Options Hash (options):

  • :site (String)

    the OAuth2 provider site host

  • :redirect_uri (String)

    the absolute URI to the Redirection Endpoint for use in authorization grants and token exchange

  • :authorize_url (String) — default: '/oauth/authorize'

    absolute or relative URL path to the Authorization 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

    HTTP method to use to authorize request (:basic_auth or :request_body)

  • :connection_opts (Hash) — default: {}

    Hash of connection options to pass to initialize Faraday with

  • :max_redirects (FixNum) — default: 5

    maximum number of redirects to follow

  • :raise_errors (Boolean) — default: true

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

  • :logger (Logger) — default: ::Logger.new($stdout)

    which logger to use when OAUTH_DEBUG is enabled

  • :extract_access_token (Proc)

    proc that takes the client and the response Hash and extracts the access token from the response (DEPRECATED)

Yields:

  • (builder)

    The Faraday connection builder



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/oauth2/client.rb', line 35

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)

  @options = {
    authorize_url: 'oauth/authorize',
    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),
  }.merge(opts)
  @options[:connection_opts][:ssl] = ssl if ssl
end

Instance Attribute Details

#connectionObject

The Faraday connection object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/oauth2/client.rb', line 65

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

#idObject (readonly)

Returns the value of attribute id.



12
13
14
# File 'lib/oauth2/client.rb', line 12

def id
  @id
end

#optionsObject

Returns the value of attribute options.



13
14
15
# File 'lib/oauth2/client.rb', line 13

def options
  @options
end

#secretObject (readonly)

Returns the value of attribute secret.



12
13
14
# File 'lib/oauth2/client.rb', line 12

def secret
  @secret
end

#siteObject

Returns the value of attribute site.



12
13
14
# File 'lib/oauth2/client.rb', line 12

def site
  @site
end

Instance Method Details

#assertionObject



223
224
225
# File 'lib/oauth2/client.rb', line 223

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

#auth_codeObject

The Authorization Code strategy



198
199
200
# File 'lib/oauth2/client.rb', line 198

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

#authorize_url(params = {}) ⇒ Object

The authorize endpoint URL of the OAuth2 provider

Parameters:

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

    additional query parameters



81
82
83
84
# File 'lib/oauth2/client.rb', line 81

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

#client_credentialsObject

The Client Credentials strategy



219
220
221
# File 'lib/oauth2/client.rb', line 219

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

#get_token(params, access_token_opts = {}, extract_access_token = , access_token_class: AccessToken) ⇒ AccessToken

Initializes an AccessToken by making a request to the token endpoint

Parameters:

  • params (Hash)

    a Hash of params for the token endpoint

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

    access token options, to pass to the AccessToken object

  • extract_access_token (Proc) (defaults to: )

    proc that extracts the access token from the response (DEPRECATED)

  • access_token_class (Class) (defaults to: AccessToken)

    class of access token for easier subclassing OAuth2::AccessToken, @version 2.0+

Returns:



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/oauth2/client.rb', line 161

def get_token(params, access_token_opts = {}, extract_access_token = options[:extract_access_token], access_token_class: AccessToken)
  params = params.map do |key, value|
    if RESERVED_PARAM_KEYS.include?(key)
      [key.to_sym, value]
    else
      [key, value]
    end
  end.to_h

  params = authenticator.apply(params)
  opts = {raise_errors: options[:raise_errors], parse: params.delete(:parse)}
  headers = params.delete(:headers) || {}
  if options[:token_method] == :post
    opts[:body] = params
    opts[:headers] = {'Content-Type' => 'application/x-www-form-urlencoded'}
  else
    opts[:params] = params
    opts[:headers] = {}
  end
  opts[:headers].merge!(headers)
  http_method = options[:token_method]
  http_method = :post if http_method == :post_with_query_string
  response = request(http_method, token_url, opts)

  # 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_with_legacy_extract(response, access_token_opts, extract_access_token)
  else
    parse_response(response, access_token_opts, access_token_class)
  end
end

#implicitObject

The Implicit strategy



205
206
207
# File 'lib/oauth2/client.rb', line 205

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

#passwordObject

The Resource Owner Password Credentials strategy



212
213
214
# File 'lib/oauth2/client.rb', line 212

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

#redirection_paramsHash

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.

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



243
244
245
246
247
248
249
# File 'lib/oauth2/client.rb', line 243

def redirection_params
  if options[:redirect_uri]
    {'redirect_uri' => options[:redirect_uri]}
  else
    {}
  end
end

#request(verb, url, opts = {}) {|req| ... } ⇒ Object

Makes a request relative to the specified site root. Updated HTTP 1.1 specification (IETF RFC 7231) relaxed the original constraint (IETF RFC 2616),

allowing the use of relative URLs in Location headers.

Parameters:

  • verb (Symbol)

    one of :get, :post, :put, :delete

  • url (String)

    URL path of request

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

    the options to make the request with

Options Hash (opts):

  • :params (Hash)

    additional query parameters for the URL of the request

  • :body (Hash, String)

    the body of the request

  • :headers (Hash)

    http request headers

  • :raise_errors (Boolean)

    whether or not to raise an OAuth2::Error on 400+ status code response for this request. Will default to client option

  • :parse (Symbol)

    @see Response::initialize

Yields:

  • (req)

    The Faraday request

See Also:



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/oauth2/client.rb', line 108

def request(verb, url, opts = {})
  url = connection.build_url(url).to_s

  begin
    response = connection.run_request(verb, url, opts[:body], opts[:headers]) do |req|
      req.params.update(opts[:params]) if opts[:params]
      yield(req) if block_given?
    end
  rescue Faraday::ConnectionFailed => e
    raise ConnectionError, e
  end

  response = Response.new(response, parse: opts[:parse])

  case response.status
  when 301, 302, 303, 307
    opts[:redirect_count] ||= 0
    opts[:redirect_count] += 1
    return response if opts[:redirect_count] > options[:max_redirects]

    if response.status == 303
      verb = :get
      opts.delete(:body)
    end
    location = response.headers['location']
    if location
      full_location = response.response.env.url.merge(location)
      request(verb, full_location, opts)
    else
      error = Error.new(response)
      raise(error, "Got #{response.status} status code, but no Location header was present")
    end
  when 200..299, 300..399
    # on non-redirecting 3xx statuses, just return the response
    response
  when 400..599
    error = Error.new(response)
    raise(error) if opts.fetch(:raise_errors, options[:raise_errors])

    response
  else
    error = Error.new(response)
    raise(error, "Unhandled status code value of #{response.status}")
  end
end

#token_url(params = nil) ⇒ Object

The token endpoint URL of the OAuth2 provider

Parameters:

  • params (Hash) (defaults to: nil)

    additional query parameters



89
90
91
# File 'lib/oauth2/client.rb', line 89

def token_url(params = nil)
  connection.build_url(options[:token_url], params).to_s
end