diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c68f16d2..8efc46f13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,28 +20,44 @@ Please file a bug if you notice a violation of semantic versioning. ### Added +### Changed + +### Deprecated + +### Removed + +### Fixed + +### Security + +## [2.0.19] - 2026-05-15 + +- TAG: [v2.0.19][2.0.19t] +- COVERAGE: 100.00% -- 515/515 lines in 14 files +- BRANCH COVERAGE: 100.00% -- 174/174 branches in 14 files +- 89.11% documented + +### Added + - [gh!707][gh!707] Add `OAuth2.config[:filtered_label]` to configure the placeholder used for filtered sensitive values in inspected objects and debug logging output by @pboling - [gh!707][gh!707] Add `OAuth2.config[:filtered_debug_keys]` to configure which key names have their values redacted from debug logging output by @pboling ### Changed - [gh!707][gh!707] Make inspect-time and debug-log filters snapshot their configuration at initialization time rather than tracking later config changes by @pboling -- Refactor sensitive-value filtering to use `auth-sanitizer` while preserving `OAuth2::FilteredAttributes` as a permanent API alias by @pboling - -### Deprecated +- [gh!714][gh!714]Refactor sensitive-value filtering to use `auth-sanitizer` while preserving `OAuth2::FilteredAttributes` as a permanent API alias by @pboling ### Removed - Remove the internal `OAuth2::ThingFilter` and `OAuth2::SanitizedLogger` implementations now provided by `auth-sanitizer` by @pboling -### Fixed - ### Security - [gh!707][gh!707] Redact sensitive values from debug logging output, including Authorization headers and common token/secret fields in headers, query strings, form bodies, and JSON payloads by @pboling - - NOTE: debug logging has always been, and remains, opt-in. It is turned off by defualt. + - NOTE: debug logging has always been, and remains, opt-in. It is turned off by default. [gh!707]: https://github.com/ruby-oauth/oauth2/pull/707 +[gh!714]: https://github.com/ruby-oauth/oauth2/pull/714 ## [2.0.18] - 2025-11-08 @@ -747,7 +763,9 @@ Please file a bug if you notice a violation of semantic versioning. [gemfiles/readme]: gemfiles/README.md -[Unreleased]: https://github.com/ruby-oauth/oauth2/compare/v2.0.18...HEAD +[Unreleased]: https://github.com/ruby-oauth/oauth2/compare/v2.0.19...HEAD +[2.0.19]: https://github.com/ruby-oauth/oauth2/compare/v2.0.18...v2.0.19 +[2.0.19t]: https://github.com/ruby-oauth/oauth2/releases/tag/v2.0.19 [2.0.18]: https://github.com/ruby-oauth/oauth2/compare/v2.0.17...v2.0.18 [2.0.18t]: https://github.com/ruby-oauth/oauth2/releases/tag/v2.0.18 [2.0.17]: https://github.com/ruby-oauth/oauth2/compare/v2.0.16...v2.0.17 diff --git a/Gemfile.lock b/Gemfile.lock index 7b4b84441..a4889eec7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - oauth2 (2.0.18) + oauth2 (2.0.19) auth-sanitizer (~> 0.1) faraday (>= 0.17.3, < 4.0) jwt (>= 1.0, < 4.0) @@ -22,7 +22,7 @@ GEM rake (>= 10) thor (>= 0.14) ast (2.4.3) - auth-sanitizer (0.1.1) + auth-sanitizer (0.1.2) version_gem (~> 1.1, >= 1.1.9) backports (3.25.3) base64 (0.3.0) @@ -386,7 +386,7 @@ CHECKSUMS ansi (1.6.0) sha256=ac9ea0c0ea8d32fb4e271348e609963ac78882f34b73836c2a02b3622e666658 appraisal2 (3.0.6) sha256=09387896b6c8c8c0ff0749af691ddff5e3168de2f06b591a80d8fd8b6394d147 ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383 - auth-sanitizer (0.1.1) sha256=e2607b13c27b005c72fbf12952afe8f8ad70156a08dadb99ae5487972290ca01 + auth-sanitizer (0.1.2) sha256=29f7638d74b2a19ff890008f1561165668a78969a4d90bc85e991128825a7c03 backports (3.25.3) sha256=94298d32dc3c40ca15633b54e282780b49e2db0c045f602ea1907e4f63a17235 base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b benchmark (0.5.0) sha256=465df122341aedcb81a2a24b4d3bd19b6c67c1530713fd533f3ff034e419236c @@ -436,7 +436,7 @@ CHECKSUMS nokogiri (1.19.3-x86_64-darwin) sha256=77f3fba57d46c53ab31e62fc6c28f705109d1bf6264356c76f132b2be5728d4d nokogiri (1.19.3-x86_64-linux-gnu) sha256=2f5078620fe12e83669b5b17311b32532a8153d02eee7ad06948b926d6080976 nokogiri (1.19.3-x86_64-linux-musl) sha256=248c906d2166eca5efb56d52fdee5f9a1f51d69a72e2b64fdac647b4ce39ea3f - oauth2 (2.0.18) + oauth2 (2.0.19) ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912 parallel (1.28.0) sha256=33e6de1484baf2524792d178b0913fc8eb94c628d6cfe45599ad4458c638c970 parser (3.3.11.1) sha256=d17ace7aabe3e72c3cc94043714be27cc6f852f104d81aa284c2281aecc65d54 diff --git a/README.md b/README.md index 246e049bc..d067f9a00 100644 --- a/README.md +++ b/README.md @@ -1514,7 +1514,7 @@ Thanks for RTFM. ☺️ [📌gitmoji]: https://gitmoji.dev [📌gitmoji-img]: https://img.shields.io/badge/gitmoji_commits-%20%F0%9F%98%9C%20%F0%9F%98%8D-34495e.svg?style=flat-square [🧮kloc]: https://www.youtube.com/watch?v=dQw4w9WgXcQ -[🧮kloc-img]: https://img.shields.io/badge/KLOC-0.526-FFDD67.svg?style=for-the-badge&logo=YouTube&logoColor=blue +[🧮kloc-img]: https://img.shields.io/badge/KLOC-0.515-FFDD67.svg?style=for-the-badge&logo=YouTube&logoColor=blue [🔐security]: SECURITY.md [🔐security-img]: https://img.shields.io/badge/security-policy-259D6C.svg?style=flat [🔐irp]: IRP.md diff --git a/REEK b/REEK index e69de29bb..c0f05d1fe 100644 --- a/REEK +++ b/REEK @@ -0,0 +1,2 @@ +./reek: 1: Error:: not found +./reek: 2: Error:: not found diff --git a/docs/OAuth2/AccessToken.html b/docs/OAuth2/AccessToken.html index 686f2ca9d..e79bd4c9c 100644 --- a/docs/OAuth2/AccessToken.html +++ b/docs/OAuth2/AccessToken.html @@ -6,13 +6,13 @@ Class: OAuth2::AccessToken - — Documentation by YARD 0.9.38 + — Documentation by YARD 0.9.43 - + - + + + + + + + + + + + + + + +
+ + +

Class: OAuth2::Authenticator + + + +

+
+ +
+
Inherits:
+
+ Object + +
    +
  • Object
  • + + + +
+ show all + +
+
+ + + + + + +
+
Includes:
+
FilteredAttributes
+
+ + + + + + +
+
Defined in:
+
lib/oauth2/authenticator.rb +
+
+ +
+ +

Overview

+
+

Builds and applies client authentication to token and revoke requests.

+ +

Depending on the selected mode, credentials are applied as Basic Auth
+headers, request body parameters, or only the client_id is sent (TLS).

+ + +
+
+
+ + +
+ + + +

Instance Attribute Summary collapse

+ + + + + + +

+ Class Method Summary + collapse +

+ + + + +

+ Instance Method Summary + collapse +

+ + + + + + +
+

Constructor Details

+ +
+

+ + #initialize(id, secret, mode) ⇒ Authenticator + + + + + +

+
+

Create a new Authenticator

+ + +
+
+
+

Parameters:

+
    + +
  • + + id + + + (String, nil) + + + + — +

    Client identifier

    +
    + +
  • + +
  • + + secret + + + (String, nil) + + + + — +

    Client secret

    +
    + +
  • + +
  • + + mode + + + (Symbol, String) + + + + — +

    Authentication mode

    +
    + +
  • + +
+ + +
+ + + + +
+
+
+
+24
+25
+26
+27
+28
+
+
# File 'lib/oauth2/authenticator.rb', line 24
+
+def initialize(id, secret, mode)
+  @id = id
+  @secret = secret
+  @mode = mode
+end
+
+
+ +
+ +
+

Instance Attribute Details

+ + + +
+

+ + #idSymbol, ... (readonly) + + + + + +

+
+ + + +
+
+
+ +

Returns:

+
    + +
  • + + + (Symbol, String) + + + + — +

    Authentication mode (e.g., :basic_auth, :request_body, :tls_client_auth, :private_key_jwt)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Client identifier

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Client secret (filtered in inspected output)

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+16
+17
+18
+
+
# File 'lib/oauth2/authenticator.rb', line 16
+
+def id
+  @id
+end
+
+
+ + + +
+

+ + #modeSymbol, ... (readonly) + + + + + +

+
+ + + +
+
+
+ +

Returns:

+
    + +
  • + + + (Symbol, String) + + + + — +

    Authentication mode (e.g., :basic_auth, :request_body, :tls_client_auth, :private_key_jwt)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Client identifier

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Client secret (filtered in inspected output)

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+16
+17
+18
+
+
# File 'lib/oauth2/authenticator.rb', line 16
+
+def mode
+  @mode
+end
+
+
+ + + +
+

+ + #secretSymbol, ... (readonly) + + + + + +

+
+ + + +
+
+
+ +

Returns:

+
    + +
  • + + + (Symbol, String) + + + + — +

    Authentication mode (e.g., :basic_auth, :request_body, :tls_client_auth, :private_key_jwt)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Client identifier

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Client secret (filtered in inspected output)

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+16
+17
+18
+
+
# File 'lib/oauth2/authenticator.rb', line 16
+
+def secret
+  @secret
+end
+
+
+ +
+ + +
+

Class Method Details

+ + +
+

+ + .encode_basic_auth(user, password) ⇒ String + + + + + +

+
+

Encodes a Basic Authorization header value for the provided credentials.

+ + +
+
+
+

Parameters:

+
    + +
  • + + user + + + (String) + + + + — +

    The client identifier

    +
    + +
  • + +
  • + + password + + + (String) + + + + — +

    The client secret

    +
    + +
  • + +
+ +

Returns:

+
    + +
  • + + + (String) + + + + — +

    The value to use for the Authorization header

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+60
+61
+62
+
+
# File 'lib/oauth2/authenticator.rb', line 60
+
+def encode_basic_auth(user, password)
+  "Basic #{Base64.strict_encode64("#{user}:#{password}")}"
+end
+
+
+ +
+ +
+

Instance Method Details

+ + +
+

+ + #apply(params) ⇒ Hash + + + + + +

+
+

Apply the request credentials used to authenticate to the Authorization Server

+ +

Depending on the configuration, this might be as request params or as an
+Authorization header.

+ +

User-provided params and header take precedence.

+ + +
+
+
+

Parameters:

+
    + +
  • + + params + + + (Hash) + + + + — +

    a Hash of params for the token endpoint

    +
    + +
  • + +
+ +

Returns:

+
    + +
  • + + + (Hash) + + + + — +

    params amended with appropriate authentication details

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+
+
# File 'lib/oauth2/authenticator.rb', line 39
+
+def apply(params)
+  case mode.to_sym
+  when :basic_auth
+    apply_basic_auth(params)
+  when :request_body
+    apply_params_auth(params)
+  when :tls_client_auth
+    apply_client_id(params)
+  when :private_key_jwt
+    params
+  else
+    raise NotImplementedError
+  end
+end
+
+
+ +
+ +
+ + + +
+ + diff --git a/docs/OAuth2/Client.html b/docs/OAuth2/Client.html index e69de29bb..59619d587 100644 --- a/docs/OAuth2/Client.html +++ b/docs/OAuth2/Client.html @@ -0,0 +1,2660 @@ + + + + + + + Class: OAuth2::Client + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Class: OAuth2::Client + + + +

+
+ +
+
Inherits:
+
+ Object + +
    +
  • Object
  • + + + +
+ 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

+ + + + + + +

+ Instance Method Summary + collapse +

+ + + + + + +
+

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. When debug logging is enabled, sensitive values are filtered using Auth::Sanitizer::SanitizedLogger initialized from OAuth2.config[:filtered_label] and the key names in OAuth2.config[:filtered_debug_keys].

    +
    + +
  • + +
  • + :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

+ + + +
+

+ + #connectionFaraday::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
+
+
+ + + +
+

+ + #idObject (readonly) + + + + + +

+
+

Returns the value of attribute id.

+ + +
+
+
+ + +
+ + + + +
+
+
+
+26
+27
+28
+
+
# File 'lib/oauth2/client.rb', line 26
+
+def id
+  @id
+end
+
+
+ + + +
+

+ + #optionsObject + + + + + +

+
+

Returns the value of attribute options.

+ + +
+
+
+ + +
+ + + + +
+
+
+
+27
+28
+29
+
+
# File 'lib/oauth2/client.rb', line 27
+
+def options
+  @options
+end
+
+
+ + + +
+

+ + #secretObject (readonly) + + + + + +

+
+

Returns the value of attribute secret.

+ + +
+
+
+ + +
+ + + + +
+
+
+
+26
+27
+28
+
+
# File 'lib/oauth2/client.rb', line 26
+
+def secret
+  @secret
+end
+
+
+ + + +
+

+ + #siteObject + + + + + +

+
+

Returns the value of attribute site.

+ + +
+
+
+ + +
+ + + + +
+
+
+
+26
+27
+28
+
+
# File 'lib/oauth2/client.rb', line 26
+
+def site
+  @site
+end
+
+
+ +
+ + +
+

Instance Method Details

+ + +
+

+ + #assertionOAuth2::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:

+ + +

See Also:

+ + +
+ + + + +
+
+
+
+314
+315
+316
+
+
# File 'lib/oauth2/client.rb', line 314
+
+def assertion
+  @assertion ||= OAuth2::Strategy::Assertion.new(self)
+end
+
+
+ +
+

+ + #auth_codeObject + + + + + +

+
+

The Authorization Code strategy

+ + +
+
+ + + + + +
+
+
+
+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_credentialsObject + + + + + +

+
+

The Client Credentials strategy

+ + +
+
+ + + + + +
+
+
+
+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_methodSymbol + + + + + +

+
+

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
+
+
+ +
+

+ + #implicitObject + + + + + +

+
+

The Implicit strategy

+ + +
+
+ + + + + +
+
+
+
+287
+288
+289
+
+
# File 'lib/oauth2/client.rb', line 287
+
+def implicit
+  @implicit ||= OAuth2::Strategy::Implicit.new(self)
+end
+
+
+ +
+

+ + #passwordObject + + + + + +

+
+

The Resource Owner Password Credentials strategy

+ + +
+
+ + + + + +
+
+
+
+294
+295
+296
+
+
# File 'lib/oauth2/client.rb', line 294
+
+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.

+ +

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.

+ + +
+
+ + + + + +
+
+
+
+339
+340
+341
+342
+343
+344
+345
+
+
# File 'lib/oauth2/client.rb', line 339
+
+def redirection_params
+  if options[:redirect_uri]
+    {"redirect_uri" => options[:redirect_uri]}
+  else
+    {}
+  end
+end
+
+
+ +
+

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

+
+

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

    +
    + +
  • + +
  • + + req_opts + + + (Hash) + + + (defaults to: {}) + + + — +

    the options to make the request with

    +
    + +
  • + +
+ + + + + + + + +

Options Hash (req_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 to raise an OAuth2::Error on 400+ status
    +code response for this request. Overrides the client instance setting.

    +
    + +
  • + +
  • + :parse + (Symbol) + + + + + —

    @see Response::initialize

    +
    + +
  • + +
  • + :snaky + (Boolean) + + + — default: + true + + + + —

    @see Response::initialize

    +
    + +
  • + +
+ + +

Yields:

+
    + +
  • + + + (req) + + + + — +

    The block is passed the request being made, allowing customization

    +
    + +
  • + +
+

Yield Parameters:

+
    + +
  • + + req + + + (Faraday::Request) + + + + — +

    The request object that can be modified

    +
    + +
  • + +
+

Returns:

+
    + +
  • + + + (OAuth2::Response) + + + + — +

    the response from the request

    +
    + +
  • + +
+ +

See Also:

+ + +
+ + + + +
+
+
+
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+
+
# File 'lib/oauth2/client.rb', line 146
+
+def request(verb, url, req_opts = {}, &block)
+  response = execute_request(verb, url, req_opts, &block)
+  status = response.status
+
+  case status
+  when 301, 302, 303, 307
+    req_opts[:redirect_count] ||= 0
+    req_opts[:redirect_count] += 1
+    return response if req_opts[:redirect_count] > options[:max_redirects]
+
+    if status == 303
+      verb = :get
+      req_opts.delete(:body)
+    end
+    location = response.headers["location"]
+    if location
+      full_location = response.response.env.url.merge(location)
+      request(verb, full_location, req_opts)
+    else
+      error = Error.new(response)
+      raise(error, "Got #{status} status code, but no Location header was present")
+    end
+  when 200..299, 300..399
+    # on non-redirecting 3xx statuses, return the response
+    response
+  when 400..599
+    if req_opts.fetch(:raise_errors, options[:raise_errors])
+      error = Error.new(response)
+      raise(error)
+    end
+
+    response
+  else
+    error = Error.new(response)
+    raise(error, "Unhandled status code value of #{status}")
+  end
+end
+
+
+ +
+

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

+
+ +
+ Note: +

If the token passed to the request
+is an access token, the server MAY revoke the respective refresh
+token as well.

+
+
+ +
+ Note: +

If the token passed to the request
+is a refresh token and the authorization server supports the
+revocation of access tokens, then the authorization server SHOULD
+also invalidate all access tokens based on the same authorization
+grant

+
+
+ +
+ Note: +

If the server responds with HTTP status code 503, your code must
+assume the token still exists and may retry after a reasonable delay.
+The server may include a “Retry-After” header in the response to
+indicate how long the service is expected to be unavailable to the
+requesting client.

+
+
+ +

Makes a request to revoke a token at the authorization server

+ + +
+
+
+

Parameters:

+
    + +
  • + + token + + + (String) + + + + — +

    The token to be revoked

    +
    + +
  • + +
  • + + token_type_hint + + + (String, nil) + + + (defaults to: nil) + + + — +

    A hint about the type of the token being revoked (e.g., ‘access_token’ or ‘refresh_token’)

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

    additional parameters for the token revocation

    +
    + +
  • + +
+ + + + + + + + +

Options Hash (params):

+
    + +
  • + :parse + (Symbol) + + + — default: + :automatic + + + + —

    parsing strategy for the response

    +
    + +
  • + +
  • + :snaky + (Boolean) + + + — default: + true + + + + —

    whether to convert response keys to snake_case

    +
    + +
  • + +
  • + :token_method + (Symbol) + + + — default: + :post_with_query_string + + + + —

    overrides OAuth2::Client#options[:token_method]

    +
    + +
  • + +
  • + :headers + (Hash) + + + + + —

    Additional request headers

    +
    + +
  • + +
+ + +

Yields:

+
    + +
  • + + + (req) + + + + — +

    The block is passed the request being made, allowing customization

    +
    + +
  • + +
+

Yield Parameters:

+
    + +
  • + + req + + + (Faraday::Request) + + + + — +

    The request object that can be modified

    +
    + +
  • + +
+

Returns:

+ + +

See Also:

+ + +
+ + + + +
+
+
+
+257
+258
+259
+260
+261
+262
+263
+264
+265
+
+
# File 'lib/oauth2/client.rb', line 257
+
+def revoke_token(token, token_type_hint = nil, params = {}, &block)
+  params[:token_method] ||= :post_with_query_string
+  params[:token] = token
+  params[:token_type_hint] = token_type_hint if token_type_hint
+
+  req_opts = params_to_req_opts(params)
+
+  request(http_method, revoke_url, req_opts, &block)
+end
+
+
+ +
+

+ + #revoke_url(params = nil) ⇒ String + + + + + +

+
+

The revoke endpoint URL of the OAuth2 provider

+ + +
+
+
+

Parameters:

+
    + +
  • + + params + + + (Hash, nil) + + + (defaults to: nil) + + + — +

    additional query parameters

    +
    + +
  • + +
+ +

Returns:

+
    + +
  • + + + (String) + + + + — +

    the constructed revoke URL

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+119
+120
+121
+
+
# File 'lib/oauth2/client.rb', line 119
+
+def revoke_url(params = nil)
+  connection.build_url(options[:revoke_url], params).to_s
+end
+
+
+ +
+

+ + #token_url(params = nil) ⇒ String + + + + + +

+
+

The token endpoint URL of the OAuth2 provider

+ + +
+
+
+

Parameters:

+
    + +
  • + + params + + + (Hash, nil) + + + (defaults to: nil) + + + — +

    additional query parameters

    +
    + +
  • + +
+ +

Returns:

+
    + +
  • + + + (String) + + + + — +

    the constructed token URL

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+111
+112
+113
+
+
# File 'lib/oauth2/client.rb', line 111
+
+def token_url(params = nil)
+  connection.build_url(options[:token_url], params).to_s
+end
+
+
+ +
+ +
+ + + +
+ + diff --git a/docs/OAuth2/Error.html b/docs/OAuth2/Error.html index e69de29bb..a2d313db4 100644 --- a/docs/OAuth2/Error.html +++ b/docs/OAuth2/Error.html @@ -0,0 +1,790 @@ + + + + + + + Exception: OAuth2::Error + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Exception: OAuth2::Error + + + +

+
+ +
+
Inherits:
+
+ StandardError + +
    +
  • Object
  • + + + + + +
+ show all + +
+
+ + + + + + + + + + + +
+
Defined in:
+
lib/oauth2/error.rb +
+
+ +
+ +

Overview

+
+

Represents an OAuth2 error condition.

+ +

Wraps details from an OAuth2::Response or Hash payload returned by an
+authorization server, exposing error code and description per RFC 6749.

+ + +
+
+
+ + +
+ + + +

Instance Attribute Summary collapse

+ + + + + + +

+ Instance Method Summary + collapse +

+ + + + + + +
+

Constructor Details

+ +
+

+ + #initialize(response) ⇒ Error + + + + + +

+
+

Create a new OAuth2::Error

+ + +
+
+
+

Parameters:

+
    + +
  • + + response + + + (OAuth2::Response, Hash, Object) + + + + — +

    A Response or error payload

    +
    + +
  • + +
+ + +
+ + + + +
+
+
+
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+
+
# File 'lib/oauth2/error.rb', line 18
+
+def initialize(response)
+  @response = response
+  @code = nil
+  @description = nil
+  if response.respond_to?(:parsed)
+    if response.parsed.is_a?(Hash)
+      @code = response.parsed["error"]
+      @description = response.parsed["error_description"]
+    end
+  elsif response.is_a?(Hash)
+    @code = response["error"]
+    @description = response["error_description"]
+  end
+  @body = if response.respond_to?(:body)
+    response.body
+  else
+    @response
+  end
+  message_opts = parse_error_description(@code, @description)
+  super(error_message(@body, message_opts))
+end
+
+
+ +
+ +
+

Instance Attribute Details

+ + + +
+

+ + #bodyOAuth2::Response, ... (readonly) + + + + + +

+
+ + + +
+
+
+ +

Returns:

+
    + +
  • + + + (OAuth2::Response, Hash, Object) + + + + — +

    Original response or payload used to build the error

    +
    + +
  • + +
  • + + + (String) + + + + — +

    Raw body content (if available)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Error code (e.g., ‘invalid_grant’)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Human-readable description for the error

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+13
+14
+15
+
+
# File 'lib/oauth2/error.rb', line 13
+
+def body
+  @body
+end
+
+
+ + + +
+

+ + #codeOAuth2::Response, ... (readonly) + + + + + +

+
+ + + +
+
+
+ +

Returns:

+
    + +
  • + + + (OAuth2::Response, Hash, Object) + + + + — +

    Original response or payload used to build the error

    +
    + +
  • + +
  • + + + (String) + + + + — +

    Raw body content (if available)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Error code (e.g., ‘invalid_grant’)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Human-readable description for the error

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+13
+14
+15
+
+
# File 'lib/oauth2/error.rb', line 13
+
+def code
+  @code
+end
+
+
+ + + +
+

+ + #descriptionOAuth2::Response, ... (readonly) + + + + + +

+
+ + + +
+
+
+ +

Returns:

+
    + +
  • + + + (OAuth2::Response, Hash, Object) + + + + — +

    Original response or payload used to build the error

    +
    + +
  • + +
  • + + + (String) + + + + — +

    Raw body content (if available)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Error code (e.g., ‘invalid_grant’)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Human-readable description for the error

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+13
+14
+15
+
+
# File 'lib/oauth2/error.rb', line 13
+
+def description
+  @description
+end
+
+
+ + + +
+

+ + #responseOAuth2::Response, ... (readonly) + + + + + +

+
+ + + +
+
+
+ +

Returns:

+
    + +
  • + + + (OAuth2::Response, Hash, Object) + + + + — +

    Original response or payload used to build the error

    +
    + +
  • + +
  • + + + (String) + + + + — +

    Raw body content (if available)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Error code (e.g., ‘invalid_grant’)

    +
    + +
  • + +
  • + + + (String, nil) + + + + — +

    Human-readable description for the error

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+13
+14
+15
+
+
# File 'lib/oauth2/error.rb', line 13
+
+def response
+  @response
+end
+
+
+ +
+ + +
+ + + +
+ + diff --git a/docs/OAuth2/FilteredAttributes.html b/docs/OAuth2/FilteredAttributes.html deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/OAuth2/FilteredAttributes/ClassMethods.html b/docs/OAuth2/FilteredAttributes/ClassMethods.html deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/OAuth2/Response.html b/docs/OAuth2/Response.html index e69de29bb..29eee59e3 100644 --- a/docs/OAuth2/Response.html +++ b/docs/OAuth2/Response.html @@ -0,0 +1,1634 @@ + + + + + + + Class: OAuth2::Response + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Class: OAuth2::Response + + + +

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

Overview

+
+

The Response class handles HTTP responses in the OAuth2 gem, providing methods
+to access and parse response data in various formats.

+ + +
+
+
+ +

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ +

+ Constant Summary + collapse +

+ +
+ +
DEFAULT_OPTIONS = +
+
+

Default configuration options for Response instances

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (Hash) + + + + — +

    The default options hash

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+
+
{
+  parse: :automatic,
+  snaky: true,
+  snaky_hash_klass: SnakyHash::StringKeyed,
+}.freeze
+ +
@@parsers = +
+
+

Storage for response body parser procedures

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (Hash<Symbol, Proc>) + + + + — +

    Hash of parser procs keyed by format symbol

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+
+
{
+  query: ->(body) { Rack::Utils.parse_query(body) },
+  text: ->(body) { body },
+}
+ +
@@content_types = +
+
+

Maps content types to parser symbols

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (Hash<String, Symbol>) + + + + — +

    Hash of content types mapped to parser symbols

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+
+
{
+  "application/x-www-form-urlencoded" => :query,
+  "text/plain" => :text,
+}
+ +
+ + + + + +

Instance Attribute Summary collapse

+ + + + + + +

+ Class Method Summary + collapse +

+ + + + +

+ Instance Method Summary + collapse +

+ + + + + +
+

Constructor Details

+ +
+

+ + #initialize(response, parse: :automatic, snaky: true, snaky_hash_klass: nil, **options) ⇒ OAuth2::Response + + + + + +

+
+

Initializes a Response instance

+ + +
+
+
+

Parameters:

+
    + +
  • + + response + + + (Faraday::Response) + + + + — +

    The Faraday response instance

    +
    + +
  • + +
  • + + parse + + + (Symbol) + + + (defaults to: :automatic) + + + — +

    (:automatic) How to parse the response body

    +
    + +
  • + +
  • + + snaky + + + (Boolean) + + + (defaults to: true) + + + — +

    (true) Whether to convert parsed response to snake_case using SnakyHash

    +
    + +
  • + +
  • + + snaky_hash_klass + + + (Class, nil) + + + (defaults to: nil) + + + — +

    (nil) Custom class for snake_case hash conversion

    +
    + +
  • + +
  • + + options + + + (Hash) + + + + — +

    Additional options for the response

    +
    + +
  • + +
+ + + + + + + + + + + + +

Options Hash (**options):

+
    + +
  • + :parse + (Symbol) + + + — default: + :automatic + + + + —

    Parse strategy (:query, :json, or :automatic)

    +
    + +
  • + +
  • + :snaky + (Boolean) + + + — default: + true + + + + —

    Enable/disable snake_case conversion

    +
    + +
  • + +
  • + :snaky_hash_klass + (Class) + + + — default: + SnakyHash::StringKeyed + + + + —

    Class to use for hash conversion

    +
    + +
  • + +
+ + +

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+74
+75
+76
+77
+78
+79
+80
+81
+
+
# File 'lib/oauth2/response.rb', line 74
+
+def initialize(response, parse: :automatic, snaky: true, snaky_hash_klass: nil, **options)
+  @response = response
+  @options = {
+    parse: parse,
+    snaky: snaky,
+    snaky_hash_klass: snaky_hash_klass,
+  }.merge(options)
+end
+
+
+ +
+ +
+

Instance Attribute Details

+ + + +
+

+ + #optionsHash + + + + + +

+
+

Returns The options hash for this instance.

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (Hash) + + + + — +

    The options hash for this instance

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+26
+27
+28
+
+
# File 'lib/oauth2/response.rb', line 26
+
+def options
+  @options
+end
+
+
+ + + +
+

+ + #responseFaraday::Response (readonly) + + + + + +

+
+

Returns The raw Faraday response object.

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (Faraday::Response) + + + + — +

    The raw Faraday response object

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+23
+24
+25
+
+
# File 'lib/oauth2/response.rb', line 23
+
+def response
+  @response
+end
+
+
+ +
+ + +
+

Class Method Details

+ + +
+

+ + .register_parser(key, mime_types) {|String| ... } ⇒ void + + + + + +

+
+

This method returns an undefined value.

Adds a new content type parser.

+ + +
+
+
+

Parameters:

+
    + +
  • + + key + + + (Symbol) + + + + — +

    A descriptive symbol key such as :json or :query

    +
    + +
  • + +
  • + + mime_types + + + (Array<String>, String) + + + + — +

    One or more mime types to which this parser applies

    +
    + +
  • + +
+ +

Yields:

+
    + +
  • + + + (String) + + + + — +

    Block that will be called to parse the response body

    +
    + +
  • + +
+

Yield Parameters:

+
    + +
  • + + body + + + (String) + + + + — +

    The response body to parse

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+54
+55
+56
+57
+58
+59
+60
+
+
# File 'lib/oauth2/response.rb', line 54
+
+def register_parser(key, mime_types, &block)
+  key = key.to_sym
+  @@parsers[key] = block
+  Array(mime_types).each do |mime_type|
+    @@content_types[mime_type] = key
+  end
+end
+
+
+ +
+ +
+

Instance Method Details

+ + +
+

+ + #bodyString + + + + + +

+
+

The HTTP response body

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (String) + + + + — +

    The response body or empty string if nil

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+100
+101
+102
+
+
# File 'lib/oauth2/response.rb', line 100
+
+def body
+  response.body || ""
+end
+
+
+ +
+

+ + #content_typeString? + + + + + +

+
+

Determines the content type of the response

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (String, nil) + + + + — +

    The content type or nil if headers are not present

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+134
+135
+136
+137
+138
+
+
# File 'lib/oauth2/response.rb', line 134
+
+def content_type
+  return unless response.headers
+
+  ((response.headers.values_at("content-type", "Content-Type").compact.first || "").split(";").first || "").strip.downcase
+end
+
+
+ +
+

+ + #headersHash + + + + + +

+
+

The HTTP response headers

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (Hash) + + + + — +

    The response headers

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+86
+87
+88
+
+
# File 'lib/oauth2/response.rb', line 86
+
+def headers
+  response.headers
+end
+
+
+ +
+

+ + #parsedObject, ... + + + + + +

+
+

The parsed response body

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (Object, SnakyHash::StringKeyed) + + + + — +

    The parsed response body

    +
    + +
  • + +
  • + + + (nil) + + + + — +

    If no parser is available

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+
+
# File 'lib/oauth2/response.rb', line 108
+
+def parsed
+  return @parsed if defined?(@parsed)
+
+  @parsed =
+    if parser.respond_to?(:call)
+      case parser.arity
+      when 0
+        parser.call
+      when 1
+        parser.call(body)
+      else
+        parser.call(body, response)
+      end
+    end
+
+  if options[:snaky] && @parsed.is_a?(Hash)
+    hash_klass = options[:snaky_hash_klass] || DEFAULT_OPTIONS[:snaky_hash_klass]
+    @parsed = hash_klass[@parsed]
+  end
+
+  @parsed
+end
+
+
+ +
+

+ + #parserProc, ... + + + + + +

+
+ +
+ Note: +

The parser can be supplied as the +:parse+ option in the form of a Proc
+(or other Object responding to #call) or a Symbol. In the latter case,
+the actual parser will be looked up in @@parsers by the supplied Symbol.

+
+
+ +
+ Note: +

If no +:parse+ option is supplied, the lookup Symbol will be determined
+by looking up #content_type in @@content_types.

+
+
+ +
+ Note: +

If #parser is a Proc, it will be called with no arguments, just
+#body, or #body and #response, depending on the Proc’s arity.

+
+
+ +

Determines the parser to be used for the response body

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (Proc, #call) + + + + — +

    The parser proc or callable object

    +
    + +
  • + +
  • + + + (nil) + + + + — +

    If no suitable parser is found

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+
+
# File 'lib/oauth2/response.rb', line 154
+
+def parser
+  return @parser if defined?(@parser)
+
+  @parser =
+    if options[:parse].respond_to?(:call)
+      options[:parse]
+    elsif options[:parse]
+      @@parsers[options[:parse].to_sym]
+    end
+
+  @parser ||= @@parsers[@@content_types[content_type]]
+end
+
+
+ +
+

+ + #statusInteger + + + + + +

+
+

The HTTP response status code

+ + +
+
+
+ +

Returns:

+
    + +
  • + + + (Integer) + + + + — +

    The response status code

    +
    + +
  • + +
+

Since:

+
    + +
  • + + + + + +

    1.0.0

    +
    + +
  • + +
+ +
+ + + + +
+
+
+
+93
+94
+95
+
+
# File 'lib/oauth2/response.rb', line 93
+
+def status
+  response.status
+end
+
+
+ +
+ +
+ + + +
+ + diff --git a/docs/OAuth2/Strategy/Assertion.html b/docs/OAuth2/Strategy/Assertion.html index e69de29bb..7b822ac78 100644 --- a/docs/OAuth2/Strategy/Assertion.html +++ b/docs/OAuth2/Strategy/Assertion.html @@ -0,0 +1,496 @@ + + + + + + + Class: OAuth2::Strategy::Assertion + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Class: OAuth2::Strategy::Assertion + + + +

+
+ +
+
Inherits:
+
+ Base + +
    +
  • Object
  • + + + + + +
+ show all + +
+
+ + + + + + + + + + + +
+
Defined in:
+
lib/oauth2/strategy/assertion.rb +
+
+ +
+ +

Overview

+
+

The Client Assertion Strategy

+ +

Sample usage:
+ client = OAuth2::Client.new(client_id, client_secret,
+ :site => ‘http://localhost:8080’,
+ :auth_scheme => :request_body)

+ +

claim_set = {
+ :iss => “http://localhost:3001”,
+ :aud => “http://localhost:8080/oauth2/token”,
+ :sub => “me@example.com”,
+ :exp => Time.now.utc.to_i + 3600,
+ }

+ +

encoding = {
+ :algorithm => ‘HS256’,
+ :key => ‘secret_key’,
+ }

+ +

access = client.assertion.get_token(claim_set, encoding)
+ access.token # actual access_token string
+ access.get(“/api/stuff”) # making api calls with access token in header

+ + +
+
+ + + + + + + + +

+ Instance Method Summary + collapse +

+ + + + + + + + + + + + + + + +

Methods inherited from Base

+

#initialize

+
+

Constructor Details

+ +

This class inherits a constructor from OAuth2::Strategy::Base

+ +
+ + +
+

Instance Method Details

+ + +
+

+ + #authorize_urlObject + + + + + +

+
+

Not used for this strategy

+ + +
+
+
+ +

Raises:

+
    + +
  • + + + (NotImplementedError) + + + +
  • + +
+ +
+ + + + +
+
+
+
+36
+37
+38
+
+
# File 'lib/oauth2/strategy/assertion.rb', line 36
+
+def authorize_url
+  raise(NotImplementedError, "The authorization endpoint is not used in this strategy")
+end
+
+
+ +
+

+ + #get_token(claims, encoding_opts, request_opts = {}, response_opts = {}) ⇒ Object + + + + + +

+
+

Retrieve an access token given the specified client.

+ +

For reading on JWT and claim keys:
+ @see https://github.com/jwt/ruby-jwt
+ @see https://datatracker.ietf.org/doc/html/rfc7519#section-4.1
+ @see https://datatracker.ietf.org/doc/html/rfc7523#section-3
+ @see https://www.iana.org/assignments/jwt/jwt.xhtml

+ +

There are many possible claim keys, and applications may ask for their own custom keys.
+Some typically required ones:
+ :iss (issuer)
+ :aud (audience)
+ :sub (subject) – formerly :prn https://datatracker.ietf.org/doc/html/draft-ietf-oauth-json-web-token-06#appendix-F
+ :exp, (expiration time) – in seconds, e.g. Time.now.utc.to_i + 3600

+ +

Note that this method does not validate presence of those four claim keys indicated as required by RFC 7523.
+There are endpoints that may not conform with this RFC, and this gem should still work for those use cases.

+ +

These two options are passed directly to JWT.encode. For supported encoding arguments:
+ @see https://github.com/jwt/ruby-jwt#algorithms-and-usage
+ @see https://datatracker.ietf.org/doc/html/rfc7518#section-3.1

+ +

The object type of :key may depend on the value of :algorithm. Sample arguments:
+ get_token(claim_set, {:algorithm => 'HS256', :key => 'secret_key'})
+ get_token(claim_set, {:algorithm => 'RS256', :key => OpenSSL::PKCS12.new(File.read('my_key.p12'), 'not_secret')})

+ + +
+
+
+

Parameters:

+
    + +
  • + + claims + + + (Hash) + + + + — +

    the hash representation of the claims that should be encoded as a JWT (JSON Web Token)

    +
    + +
  • + +
  • + + encoding_opts + + + (Hash) + + + + — +

    a hash containing instructions on how the JWT should be encoded

    +
    + +
  • + +
  • + + request_opts + + + (Hash) + + + (defaults to: {}) + + + — +

    options that will be used to assemble the request

    +
    + +
  • + +
  • + + response_opts + + + (Hash) + + + (defaults to: {}) + + + — +

    this will be merged with the token response to create the AccessToken object
    +@see the access_token_opts argument to Client#get_token

    +
    + +
  • + +
  • + + algorithm + + + (Hash) + + + + — +

    a customizable set of options

    +
    + +
  • + +
  • + + key + + + (Hash) + + + + — +

    a customizable set of options

    +
    + +
  • + +
+ + + + + + + + +

Options Hash (request_opts):

+
    + +
  • + :scope + (String) + + + + + —

    the url parameter scope that may be required by some endpoints
    +@see https://datatracker.ietf.org/doc/html/rfc7521#section-4.1

    +
    + +
  • + +
+ + + + + +
+ + + + +
+
+
+
+79
+80
+81
+82
+83
+84
+
+
# File 'lib/oauth2/strategy/assertion.rb', line 79
+
+def get_token(claims, encoding_opts, request_opts = {}, response_opts = {})
+  assertion = build_assertion(claims, encoding_opts)
+  params = build_request(assertion, request_opts)
+
+  @client.get_token(params, response_opts)
+end
+
+
+ +
+ +
+ + + +
+ + diff --git a/docs/OAuth2/Strategy/AuthCode.html b/docs/OAuth2/Strategy/AuthCode.html index e69de29bb..deef1c9a4 100644 --- a/docs/OAuth2/Strategy/AuthCode.html +++ b/docs/OAuth2/Strategy/AuthCode.html @@ -0,0 +1,498 @@ + + + + + + + Class: OAuth2::Strategy::AuthCode + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Class: OAuth2::Strategy::AuthCode + + + +

+
+ +
+
Inherits:
+
+ Base + +
    +
  • Object
  • + + + + + +
+ show all + +
+
+ + + + + + + + + + + +
+
Defined in:
+
lib/oauth2/strategy/auth_code.rb +
+
+ +
+ +

Overview

+
+

The Authorization Code Strategy

+ +

OAuth 2.1 notes:

+
    +
  • PKCE is required for all OAuth clients using the authorization code flow (especially public clients).
    +This library does not enforce PKCE generation/verification; implement PKCE in your application when required.
  • +
  • Redirect URIs must be compared using exact string matching by the Authorization Server.
    +This client forwards redirect_uri but does not perform server-side validation.
  • +
+ +

References:

+
    +
  • OAuth 2.1 draft: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13
  • +
  • OAuth for native apps (RFC 8252) and PKCE (RFC 7636)
  • +
+ + +
+
+ + + + + + + + +

+ Instance Method Summary + collapse +

+ + + + + + + + + + + + + + + +

Methods inherited from Base

+

#initialize

+
+

Constructor Details

+ +

This class inherits a constructor from OAuth2::Strategy::Base

+ +
+ + +
+

Instance Method Details

+ + +
+

+ + #authorize_params(params = {}) ⇒ Object + + + + + +

+
+

The required query parameters for the authorize URL

+ + +
+
+
+

Parameters:

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

    additional query parameters

    +
    + +
  • + +
+ + +
+ + + + +
+
+
+
+22
+23
+24
+
+
# File 'lib/oauth2/strategy/auth_code.rb', line 22
+
+def authorize_params(params = {})
+  params.merge("response_type" => "code", "client_id" => @client.id)
+end
+
+
+ +
+

+ + #authorize_url(params = {}) ⇒ Object + + + + + +

+
+

The authorization URL endpoint of the provider

+ + +
+
+
+

Parameters:

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

    additional query parameters for the URL

    +
    + +
  • + +
+ + +
+ + + + +
+
+
+
+29
+30
+31
+32
+
+
# File 'lib/oauth2/strategy/auth_code.rb', line 29
+
+def authorize_url(params = {})
+  assert_valid_params(params)
+  @client.authorize_url(authorize_params.merge(params))
+end
+
+
+ +
+

+ + #get_token(code, params = {}, opts = {}) ⇒ Object + + + + + +

+
+ +
+ Note: +

that you must also provide a :redirect_uri with most OAuth 2.0 providers

+
+
+ +

Retrieve an access token given the specified validation code.

+ + +
+
+
+

Parameters:

+
    + +
  • + + code + + + (String) + + + + — +

    The Authorization Code value

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

    additional params

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

    access_token_opts, @see Client#get_token

    +
    + +
  • + +
+ + +
+ + + + +
+
+
+
+40
+41
+42
+43
+44
+45
+46
+47
+48
+
+
# File 'lib/oauth2/strategy/auth_code.rb', line 40
+
+def get_token(code, params = {}, opts = {})
+  params = {"grant_type" => "authorization_code", "code" => code}.merge(@client.redirection_params).merge(params)
+  params_dup = params.dup
+  params.each_key do |key|
+    params_dup[key.to_s] = params_dup.delete(key) if key.is_a?(Symbol)
+  end
+
+  @client.get_token(params_dup, opts)
+end
+
+
+ +
+ +
+ + + +
+ + diff --git a/docs/OAuth2/Strategy/Base.html b/docs/OAuth2/Strategy/Base.html index e69de29bb..df6c6ad3e 100644 --- a/docs/OAuth2/Strategy/Base.html +++ b/docs/OAuth2/Strategy/Base.html @@ -0,0 +1,209 @@ + + + + + + + Class: OAuth2::Strategy::Base + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Class: OAuth2::Strategy::Base + + + +

+
+ +
+
Inherits:
+
+ Object + +
    +
  • Object
  • + + + +
+ show all + +
+
+ + + + + + + + + + + +
+
Defined in:
+
lib/oauth2/strategy/base.rb +
+
+ +
+ +
+

Direct Known Subclasses

+

Assertion, AuthCode, ClientCredentials, Implicit, Password

+
+ + + + + + + + +

+ Instance Method Summary + collapse +

+ + + + + +
+

Constructor Details

+ +
+

+ + #initialize(client) ⇒ Base + + + + + +

+
+

Returns a new instance of Base.

+ + +
+
+
+ + +
+ + + + +
+
+
+
+6
+7
+8
+
+
# File 'lib/oauth2/strategy/base.rb', line 6
+
+def initialize(client)
+  @client = client
+end
+
+
+ +
+ + +
+ + + +
+ + diff --git a/docs/OAuth2/Strategy/Implicit.html b/docs/OAuth2/Strategy/Implicit.html index e69de29bb..05c0fa79b 100644 --- a/docs/OAuth2/Strategy/Implicit.html +++ b/docs/OAuth2/Strategy/Implicit.html @@ -0,0 +1,435 @@ + + + + + + + Class: OAuth2::Strategy::Implicit + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Class: OAuth2::Strategy::Implicit + + + +

+
+ +
+
Inherits:
+
+ Base + +
    +
  • Object
  • + + + + + +
+ show all + +
+
+ + + + + + + + + + + +
+
Defined in:
+
lib/oauth2/strategy/implicit.rb +
+
+ +
+ +

Overview

+
+

The Implicit Strategy

+ +

IMPORTANT (OAuth 2.1): The Implicit grant (response_type=token) is omitted from the OAuth 2.1 draft specification.
+It remains here for backward compatibility with OAuth 2.0 providers. Prefer the Authorization Code flow with PKCE.

+ +

References:

+
    +
  • OAuth 2.1 draft: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13
  • +
  • Why drop implicit: https://aaronparecki.com/2019/12/12/21/its-time-for-oauth-2-dot-1
  • +
  • Background: https://fusionauth.io/learn/expert-advice/oauth/differences-between-oauth-2-oauth-2-1/
  • +
+ + +
+
+ + + + + + + + +

+ Instance Method Summary + collapse +

+ + + + + + + + + + + + + + + +

Methods inherited from Base

+

#initialize

+
+

Constructor Details

+ +

This class inherits a constructor from OAuth2::Strategy::Base

+ +
+ + +
+

Instance Method Details

+ + +
+

+ + #authorize_params(params = {}) ⇒ Object + + + + + +

+
+

The required query parameters for the authorize URL

+ + +
+
+
+

Parameters:

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

    additional query parameters

    +
    + +
  • + +
+ + +
+ + + + +
+
+
+
+20
+21
+22
+
+
# File 'lib/oauth2/strategy/implicit.rb', line 20
+
+def authorize_params(params = {})
+  params.merge("response_type" => "token", "client_id" => @client.id)
+end
+
+
+ +
+

+ + #authorize_url(params = {}) ⇒ Object + + + + + +

+
+

The authorization URL endpoint of the provider

+ + +
+
+
+

Parameters:

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

    additional query parameters for the URL

    +
    + +
  • + +
+ + +
+ + + + +
+
+
+
+27
+28
+29
+30
+
+
# File 'lib/oauth2/strategy/implicit.rb', line 27
+
+def authorize_url(params = {})
+  assert_valid_params(params)
+  @client.authorize_url(authorize_params.merge(params))
+end
+
+
+ +
+

+ + #get_tokenObject + + + + + +

+
+

Not used for this strategy

+ + +
+
+
+ +

Raises:

+
    + +
  • + + + (NotImplementedError) + + + +
  • + +
+ +
+ + + + +
+
+
+
+35
+36
+37
+
+
# File 'lib/oauth2/strategy/implicit.rb', line 35
+
+def get_token(*)
+  raise(NotImplementedError, "The token is accessed differently in this strategy")
+end
+
+
+ +
+ +
+ + + +
+ + diff --git a/docs/class_list.html b/docs/class_list.html index e69de29bb..f21d031f4 100644 --- a/docs/class_list.html +++ b/docs/class_list.html @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + Class List + + + +
+
+

Class List

+ + + +
+ + +
+ + diff --git a/docs/css/common.css b/docs/css/common.css index cf25c4523..37b035a61 100644 --- a/docs/css/common.css +++ b/docs/css/common.css @@ -1 +1 @@ -/* Override this file with custom rules */ \ No newline at end of file +/* Override this file with custom rules */ diff --git a/docs/css/full_list.css b/docs/css/full_list.css index 6eef5e4a0..5adbd84ac 100644 --- a/docs/css/full_list.css +++ b/docs/css/full_list.css @@ -1,58 +1,206 @@ body { - margin: 0; - font-family: "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif; - font-size: 13px; - height: 101%; - overflow-x: hidden; - background: #fafafa; + margin: 0; + font-family: "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif; + font-size: 13px; + height: 101%; + overflow-x: hidden; + background: #fafafa; } -h1 { padding: 12px 10px; padding-bottom: 0; margin: 0; font-size: 1.4em; } -.clear { clear: both; } -.fixed_header { position: fixed; background: #fff; width: 100%; padding-bottom: 10px; margin-top: 0; top: 0; z-index: 9999; height: 70px; } -#search { position: absolute; right: 5px; top: 9px; padding-left: 24px; } -#content.insearch #search, #content.insearch #noresults { background: url(data:image/gif;base64,R0lGODlhEAAQAPYAAP///wAAAPr6+pKSkoiIiO7u7sjIyNjY2J6engAAAI6OjsbGxjIyMlJSUuzs7KamppSUlPLy8oKCghwcHLKysqSkpJqamvT09Pj4+KioqM7OzkRERAwMDGBgYN7e3ujo6Ly8vCoqKjY2NkZGRtTU1MTExDw8PE5OTj4+PkhISNDQ0MrKylpaWrS0tOrq6nBwcKysrLi4uLq6ul5eXlxcXGJiYoaGhuDg4H5+fvz8/KKiohgYGCwsLFZWVgQEBFBQUMzMzDg4OFhYWBoaGvDw8NbW1pycnOLi4ubm5kBAQKqqqiQkJCAgIK6urnJyckpKSjQ0NGpqatLS0sDAwCYmJnx8fEJCQlRUVAoKCggICLCwsOTk5ExMTPb29ra2tmZmZmhoaNzc3KCgoBISEiIiIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCAAAACwAAAAAEAAQAAAHaIAAgoMgIiYlg4kACxIaACEJCSiKggYMCRselwkpghGJBJEcFgsjJyoAGBmfggcNEx0flBiKDhQFlIoCCA+5lAORFb4AJIihCRbDxQAFChAXw9HSqb60iREZ1omqrIPdJCTe0SWI09GBACH5BAkIAAAALAAAAAAQABAAAAdrgACCgwc0NTeDiYozCQkvOTo9GTmDKy8aFy+NOBA7CTswgywJDTIuEjYFIY0JNYMtKTEFiRU8Pjwygy4ws4owPyCKwsMAJSTEgiQlgsbIAMrO0dKDGMTViREZ14kYGRGK38nHguHEJcvTyIEAIfkECQgAAAAsAAAAABAAEAAAB2iAAIKDAggPg4iJAAMJCRUAJRIqiRGCBI0WQEEJJkWDERkYAAUKEBc4Po1GiKKJHkJDNEeKig4URLS0ICImJZAkuQAhjSi/wQyNKcGDCyMnk8u5rYrTgqDVghgZlYjcACTA1sslvtHRgQAh+QQJCAAAACwAAAAAEAAQAAAHZ4AAgoOEhYaCJSWHgxGDJCQARAtOUoQRGRiFD0kJUYWZhUhKT1OLhR8wBaaFBzQ1NwAlkIszCQkvsbOHL7Y4q4IuEjaqq0ZQD5+GEEsJTDCMmIUhtgk1lo6QFUwJVDKLiYJNUd6/hoEAIfkECQgAAAAsAAAAABAAEAAAB2iAAIKDhIWGgiUlh4MRgyQkjIURGRiGGBmNhJWHm4uen4ICCA+IkIsDCQkVACWmhwSpFqAABQoQF6ALTkWFnYMrVlhWvIKTlSAiJiVVPqlGhJkhqShHV1lCW4cMqSkAR1ofiwsjJyqGgQAh+QQJCAAAACwAAAAAEAAQAAAHZ4AAgoOEhYaCJSWHgxGDJCSMhREZGIYYGY2ElYebi56fhyWQniSKAKKfpaCLFlAPhl0gXYNGEwkhGYREUywag1wJwSkHNDU3D0kJYIMZQwk8MjPBLx9eXwuETVEyAC/BOKsuEjYFhoEAIfkECQgAAAAsAAAAABAAEAAAB2eAAIKDhIWGgiUlh4MRgyQkjIURGRiGGBmNhJWHm4ueICImip6CIQkJKJ4kigynKaqKCyMnKqSEK05StgAGQRxPYZaENqccFgIID4KXmQBhXFkzDgOnFYLNgltaSAAEpxa7BQoQF4aBACH5BAkIAAAALAAAAAAQABAAAAdogACCg4SFggJiPUqCJSWGgkZjCUwZACQkgxGEXAmdT4UYGZqCGWQ+IjKGGIUwPzGPhAc0NTewhDOdL7Ykji+dOLuOLhI2BbaFETICx4MlQitdqoUsCQ2vhKGjglNfU0SWmILaj43M5oEAOwAAAAAAAAAAAA==) no-repeat center left; } -#full_list { padding: 0; list-style: none; margin-left: 0; margin-top: 80px; font-size: 1.1em; } -#full_list ul { padding: 0; } -#full_list li { padding: 0; margin: 0; list-style: none; } -#full_list li .item { padding: 5px 5px 5px 12px; } -#noresults { padding: 7px 12px; background: #fff; } -#content.insearch #noresults { margin-left: 7px; } -li.collapsed ul { display: none; } -li a.toggle { cursor: default; position: relative; left: -5px; top: 4px; text-indent: -999px; width: 10px; height: 9px; margin-left: -10px; display: block; float: left; background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAASCAYAAABb0P4QAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAK8AAACvABQqw0mAAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTM5jWRgMAAAAVdEVYdENyZWF0aW9uIFRpbWUAMy8xNC8wOeNZPpQAAAE2SURBVDiNrZTBccIwEEXfelIAHUA6CZ24BGaWO+FuzZAK4k6gg5QAdGAq+Bxs2Yqx7BzyL7Llp/VfzZeQhCTc/ezuGzKKnKSzpCxXJM8fwNXda3df5RZETlIt6YUzSQDs93sl8w3wBZxCCE10GM1OcWbWjB2mWgEH4Mfdyxm3PSepBHibgQE2wLe7r4HjEidpnXMYdQPKEMJcsZ4zs2POYQOcaPfwMVOo58zsAdMt18BuoVDPxUJRacELbXv3hUIX2vYmOUvi8C8ydz/ThjXrqKqqLbDIAdsCKBd+Wo7GWa7o9qzOQHVVVXeAbs+yHHCH4aTsaCOQqunmUy1yBUAXkdMIfMlgF5EXLo2OpV/c/Up7jG4hhHcYLgWzAZXUc2b2ixsfvc/RmNNfOXD3Q/oeL9axJE1yT9IOoUu6MGUkAAAAAElFTkSuQmCC) no-repeat bottom left; } -li.collapsed a.toggle { cursor: default; background-position: top left; } -li { color: #666; cursor: pointer; } -li.deprecated { text-decoration: line-through; font-style: italic; } -li.odd { background: #f0f0f0; } -li.even { background: #fafafa; } -.item:hover { background: #ddd; } -li small:before { content: "("; } -li small:after { content: ")"; } -li small.search_info { display: none; } -a, a:visited { text-decoration: none; color: #05a; } -li.clicked > .item { background: #05a; color: #ccc; } -li.clicked > .item a, li.clicked > .item a:visited { color: #eee; } -li.clicked > .item a.toggle { opacity: 0.5; background-position: bottom right; } -li.collapsed.clicked a.toggle { background-position: top right; } -#search input { border: 1px solid #bbb; border-radius: 3px; } -#full_list_nav { margin-left: 10px; font-size: 0.9em; display: block; color: #aaa; } -#full_list_nav a, #nav a:visited { color: #358; } -#full_list_nav a:hover { background: transparent; color: #5af; } -#full_list_nav span:after { content: ' | '; } -#full_list_nav span:last-child:after { content: ''; } +h1 { + padding: 12px 10px; + padding-bottom: 0; + margin: 0; + font-size: 1.4em; +} +.clear { + clear: both; +} +.fixed_header { + position: fixed; + background: #fff; + width: 100%; + padding-bottom: 10px; + margin-top: 0; + top: 0; + z-index: 9999; + height: 70px; +} +#search { + position: absolute; + right: 5px; + top: 9px; + padding-left: 24px; +} +#noresults { + padding: 7px 12px; + background: #fff; +} +#content.insearch #search, +#content.insearch #noresults { + background: url(data:image/gif;base64,R0lGODlhEAAQAPYAAP///wAAAPr6+pKSkoiIiO7u7sjIyNjY2J6engAAAI6OjsbGxjIyMlJSUuzs7KamppSUlPLy8oKCghwcHLKysqSkpJqamvT09Pj4+KioqM7OzkRERAwMDGBgYN7e3ujo6Ly8vCoqKjY2NkZGRtTU1MTExDw8PE5OTj4+PkhISNDQ0MrKylpaWrS0tOrq6nBwcKysrLi4uLq6ul5eXlxcXGJiYoaGhuDg4H5+fvz8/KKiohgYGCwsLFZWVgQEBFBQUMzMzDg4OFhYWBoaGvDw8NbW1pycnOLi4ubm5kBAQKqqqiQkJCAgIK6urnJyckpKSjQ0NGpqatLS0sDAwCYmJnx8fEJCQlRUVAoKCggICLCwsOTk5ExMTPb29ra2tmZmZmhoaNzc3KCgoBISEiIiIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCAAAACwAAAAAEAAQAAAHaIAAgoMgIiYlg4kACxIaACEJCSiKggYMCRselwkpghGJBJEcFgsjJyoAGBmfggcNEx0flBiKDhQFlIoCCA+5lAORFb4AJIihCRbDxQAFChAXw9HSqb60iREZ1omqrIPdJCTe0SWI09GBACH5BAkIAAAALAAAAAAQABAAAAdrgACCgwc0NTeDiYozCQkvOTo9GTmDKy8aFy+NOBA7CTswgywJDTIuEjYFIY0JNYMtKTEFiRU8Pjwygy4ws4owPyCKwsMAJSTEgiQlgsbIAMrO0dKDGMTViREZ14kYGRGK38nHguHEJcvTyIEAIfkECQgAAAAsAAAAABAAEAAAB2iAAIKDAggPg4iJAAMJCRUAJRIqiRGCBI0WQEEJJkWDERkYAAUKEBc4Po1GiKKJHkJDNEeKig4URLS0ICImJZAkuQAhjSi/wQyNKcGDCyMnk8u5rYrTgqDVghgZlYjcACTA1sslvtHRgQAh+QQJCAAAACwAAAAAEAAQAAAHZ4AAgoOEhYaCJSWHgxGDJCQARAtOUoQRGRiFD0kJUYWZhUhKT1OLhR8wBaaFBzQ1NwAlkIszCQkvsbOHL7Y4q4IuEjaqq0ZQD5+GEEsJTDCMmIUhtgk1lo6QFUwJVDKLiYJNUd6/hoEAIfkECQgAAAAsAAAAABAAEAAAB2iAAIKDhIWGgiUlh4MRgyQkjIURGRiGGBmNhJWHm4uen4ICCA+IkIsDCQkVACWmhwSpFqAABQoQF6ALTkWFnYMrVlhWvIKTlSAiJiVVPqlGhJkhqShHV1lCW4cMqSkAR1ofiwsjJyqGgQAh+QQJCAAAACwAAAAAEAAQAAAHZ4AAgoOEhYaCJSWHgxGDJCSMhREZGIYYGY2ElYebi56fhyWQniSKAKKfpaCLFlAPhl0gXYNGEwkhGYREUywag1wJwSkHNDU3D0kJYIMZQwk8MjPBLx9eXwuETVEyAC/BOKsuEjYFhoEAIfkECQgAAAAsAAAAABAAEAAAB2eAAIKDhIWGgiUlh4MRgyQkjIURGRiGGBmNhJWHm4ueICImip6CIQkJKJ4kigynKaqKCyMnKqSEK05StgAGQRxPYZaENqccFgIID4KXmQBhXFkzDgOnFYLNgltaSAAEpxa7BQoQF4aBACH5BAkIAAAALAAAAAAQABAAAAdogACCg4SFggJiPUqCJSWGgkZjCUwZACQkgxGEXAmdT4UYGZqCGWQ+IjKGGIUwPzGPhAc0NTewhDOdL7Ykji+dOLuOLhI2BbaFETICx4MlQitdqoUsCQ2vhKGjglNfU0SWmILaj43M5oEAOwAAAAAAAAAAAA==) + no-repeat center left; +} +#full_list { + padding: 0; + list-style: none; + margin-left: 0; + margin-top: 80px; + font-size: 1.1em; +} +#full_list ul { + padding: 0; +} +#full_list li { + padding: 0; + margin: 0; + list-style: none; +} +#full_list li .item { + padding: 5px 5px 5px 12px; +} +#content.insearch #noresults { + margin-left: 7px; +} +#full_list li { + color: #666; + cursor: normal; + white-space: nowrap; +} +#full_list li.collapsed ul { + display: none; +} +#full_list li a.toggle { + cursor: default; + position: relative; + left: -5px; + top: 4px; + text-indent: -999px; + width: 10px; + height: 9px; + margin-left: -10px; + display: block; + float: left; + background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAASCAYAAABb0P4QAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAK8AAACvABQqw0mAAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTM5jWRgMAAAAVdEVYdENyZWF0aW9uIFRpbWUAMy8xNC8wOeNZPpQAAAE2SURBVDiNrZTBccIwEEXfelIAHUA6CZ24BGaWO+FuzZAK4k6gg5QAdGAq+Bxs2Yqx7BzyL7Llp/VfzZeQhCTc/ezuGzKKnKSzpCxXJM8fwNXda3df5RZETlIt6YUzSQDs93sl8w3wBZxCCE10GM1OcWbWjB2mWgEH4Mfdyxm3PSepBHibgQE2wLe7r4HjEidpnXMYdQPKEMJcsZ4zs2POYQOcaPfwMVOo58zsAdMt18BuoVDPxUJRacELbXv3hUIX2vYmOUvi8C8ydz/ThjXrqKqqLbDIAdsCKBd+Wo7GWa7o9qzOQHVVVXeAbs+yHHCH4aTsaCOQqunmUy1yBUAXkdMIfMlgF5EXLo2OpV/c/Up7jG4hhHcYLgWzAZXUc2b2ixsfvc/RmNNfOXD3Q/oeL9axJE1yT9IOoUu6MGUkAAAAAElFTkSuQmCC) + no-repeat bottom left; +} +#full_list li.collapsed a.toggle { + cursor: default; + background-position: top left; +} +#full_list li.deprecated { + text-decoration: line-through; + font-style: italic; +} +#full_list li.odd { + background: #f0f0f0; +} +#full_list li.even { + background: #fafafa; +} +#full_list .item:hover { + background: #ddd; +} +#full_list li small:before { + content: "("; +} +#full_list li small:after { + content: ")"; +} +#full_list li small.search_info { + display: none; +} +a, +a:visited { + text-decoration: none; + color: #05a; +} +#full_list li.clicked > .item { + background: #05a; + color: #ccc; +} +#full_list li.clicked > .item a, +#full_list li.clicked > .item a:visited { + color: #eee; +} +#full_list li.clicked > .item a.toggle { + opacity: 0.5; + background-position: bottom right; +} +#full_list li.collapsed.clicked a.toggle { + background-position: top right; +} +#search input { + border: 1px solid #bbb; + border-radius: 3px; +} +#full_list_nav { + margin-left: 10px; + font-size: 0.9em; + display: block; + color: #aaa; +} +#full_list_nav a, +#nav a:visited { + color: #358; +} +#full_list_nav a:hover { + background: transparent; + color: #5af; +} +#full_list_nav span:after { + content: " | "; +} +#full_list_nav span:last-child:after { + content: ""; +} -#content h1 { margin-top: 0; } -li { white-space: nowrap; cursor: normal; } -li small { display: block; font-size: 0.8em; } -li small:before { content: ""; } -li small:after { content: ""; } -li small.search_info { display: none; } -#search { width: 170px; position: static; margin: 3px; margin-left: 10px; font-size: 0.9em; color: #666; padding-left: 0; padding-right: 24px; } -#content.insearch #search { background-position: center right; } -#search input { width: 110px; } +#content h1 { + margin-top: 0; +} +#full_list li small { + display: block; + font-size: 0.8em; +} +#full_list li small:before { + content: ""; +} +#full_list li small:after { + content: ""; +} +#full_list li small.search_info { + display: none; +} +#search { + width: 170px; + position: static; + margin: 3px; + margin-left: 10px; + font-size: 0.9em; + color: #666; + padding-left: 0; + padding-right: 24px; +} +#content.insearch #search { + background-position: center right; +} +#search input { + width: 110px; +} -#full_list.insearch ul { display: block; } -#full_list.insearch .item { display: none; } -#full_list.insearch .found { display: block; padding-left: 11px !important; } -#full_list.insearch li a.toggle { display: none; } -#full_list.insearch li small.search_info { display: block; } +#full_list.insearch ul { + display: block; +} +#full_list.insearch .item { + display: none; +} +#full_list.insearch .found { + display: block; + padding-left: 11px; +} +#full_list.insearch li a.toggle { + display: none; +} +#full_list.insearch li small.search_info { + display: block; +} diff --git a/docs/css/style.css b/docs/css/style.css index 2e909a2ce..e915fc06d 100644 --- a/docs/css/style.css +++ b/docs/css/style.css @@ -1,490 +1,1089 @@ html { - width: 100%; - height: 100%; + width: 100%; + height: 100%; } body { - font-family: "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif; - font-size: 13px; - width: 100%; - margin: 0; - padding: 0; - display: flex; + font-family: "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif; + font-size: 13px; + width: 100%; + margin: 0; + padding: 0; + display: flex; } #nav { - position: relative; - width: 100%; - height: 100%; - border: 0; - border-right: 1px dotted #eee; - overflow: auto; + position: relative; + width: 100%; + height: 100%; + border: 0; + border-right: 1px dotted #eee; + overflow: auto; } .nav_wrap { - margin: 0; - padding: 0; - width: 20%; - height: 100%; - position: relative; - display: flex; - flex-shrink: 0; + margin: 0; + padding: 0; + width: 20%; + height: 100%; + position: relative; + display: flex; + flex-shrink: 0; } #resizer { - position: absolute; - right: -5px; - top: 0; - width: 10px; - height: 100%; - cursor: col-resize; - z-index: 9999; + position: absolute; + right: -5px; + top: 0; + width: 10px; + height: 100%; + cursor: col-resize; + z-index: 9999; } #main { - flex: 5 1; - outline: none; - position: relative; - background: #fff; - padding: 1.2em; - padding-top: 0.2em; - box-sizing: border-box; + flex: 5 1; + outline: none; + position: relative; + background: #fff; + padding: 1.2em; + padding-top: 0.2em; + box-sizing: border-box; +} +#main_progress { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 3px; + overflow: hidden; + opacity: 0; + z-index: 10001; + pointer-events: none; + transition: opacity 0.18s ease; +} +#main_progress::before { + content: ""; + display: block; + width: var(--yard-progress, 0%); + height: 100%; + background: linear-gradient(90deg, #1b6ac9 0%, #4ea3ff 100%); + transition: width 0.08s linear; +} +body.loading #main_progress { + opacity: 1; +} +body.loading #main_progress::before { + animation: yard-progress-breathe 1.6s ease-in-out infinite; +} + +@keyframes yard-progress-breathe { + 0% { + filter: saturate(0.92) brightness(0.94); + } + 50% { + filter: saturate(1.08) brightness(1.08); + } + 100% { + filter: saturate(0.92) brightness(0.94); + } } @media (max-width: 920px) { - body { display: block; } - .nav_wrap { width: 80vw !important; top: 0; right: 0; overflow: visible; position: absolute; } - #resizer { display: none; } - #nav { - z-index: 9999; - background: #fff; - display: none; - position: absolute; - top: 40px; - right: 12px; - width: 500px; - max-width: 80%; - height: 80%; - overflow-y: scroll; - border: 1px solid #999; - border-collapse: collapse; - box-shadow: -7px 5px 25px #aaa; - border-radius: 2px; - } + body { + display: block; + } + .nav_wrap { + width: 80vw; + top: 0; + right: 0; + overflow: visible; + position: absolute; + } + #resizer { + display: none; + } + #nav { + z-index: 9999; + background: #fff; + display: none; + position: absolute; + top: 40px; + right: 12px; + width: 500px; + max-width: 80%; + height: 80%; + overflow-y: scroll; + border: 1px solid #999; + border-collapse: collapse; + box-shadow: -7px 5px 25px #aaa; + border-radius: 2px; + } } @media (min-width: 920px) { - body { height: 100%; overflow: hidden; } - #main { height: 100%; overflow: auto; } - #search { display: none; } + body { + height: 100%; + overflow: hidden; + } + #main { + height: 100%; + overflow: auto; + } + #search { + display: none; + } } @media (max-width: 320px) { - body { height: 100%; overflow: hidden; overflow-wrap: break-word; } - #main { height: 100%; overflow: auto; } + body { + height: 100%; + overflow: hidden; + overflow-wrap: break-word; + } + #main { + height: 100%; + overflow: auto; + } } -#main img { max-width: 100%; } -h1 { font-size: 25px; margin: 1em 0 0.5em; padding-top: 4px; border-top: 1px dotted #d5d5d5; } -h1.noborder { border-top: 0px; margin-top: 0; padding-top: 4px; } -h1.title { margin-bottom: 10px; } -h1.alphaindex { margin-top: 0; font-size: 22px; } +#main img { + max-width: 100%; +} +h1 { + font-size: 25px; + margin: 1em 0 0.5em; + padding-top: 4px; + border-top: 1px dotted #d5d5d5; +} +h1.noborder { + border-top: 0px; + margin-top: 0; + padding-top: 4px; +} +h1.title { + margin-bottom: 10px; +} +h1.alphaindex { + margin-top: 0; + font-size: 22px; +} h2 { - padding: 0; - padding-bottom: 3px; - border-bottom: 1px #aaa solid; - font-size: 1.4em; - margin: 1.8em 0 0.5em; - position: relative; -} -h2 small { font-weight: normal; font-size: 0.7em; display: inline; position: absolute; right: 0; } + padding: 0; + padding-bottom: 3px; + border-bottom: 1px #aaa solid; + font-size: 1.4em; + margin: 1.8em 0 0.5em; + position: relative; +} +h2 small { + font-weight: normal; + font-size: 0.7em; + display: inline; + position: absolute; + right: 0; +} +a { + font-weight: 550; +} h2 small a { - display: block; - height: 20px; - border: 1px solid #aaa; - border-bottom: 0; - border-top-left-radius: 5px; - background: #f8f8f8; - position: relative; - padding: 2px 7px; -} -a { font-weight: 550; } -.clear { clear: both; } -.inline { display: inline; } -.inline p:first-child { display: inline; } -.docstring, .tags, #filecontents { font-size: 15px; line-height: 1.5145em; } -.docstring p > code, .docstring p > tt, .tags p > code, .tags p > tt { - color: #c7254e; background: #f9f2f4; padding: 2px 4px; font-size: 1em; - border-radius: 4px; -} -.docstring h1, .docstring h2, .docstring h3, .docstring h4 { padding: 0; border: 0; border-bottom: 1px dotted #bbb; } -.docstring h1 { font-size: 1.2em; } -.docstring h2 { font-size: 1.1em; } -.docstring h3, .docstring h4 { font-size: 1em; border-bottom: 0; padding-top: 10px; } -.summary_desc .object_link a, .docstring .object_link a { - font-family: monospace; font-size: 1.05em; - color: #05a; background: #EDF4FA; padding: 2px 4px; font-size: 1em; - border-radius: 4px; -} -.rdoc-term { padding-right: 25px; font-weight: bold; } -.rdoc-list p { margin: 0; padding: 0; margin-bottom: 4px; } -.summary_desc pre.code .object_link a, .docstring pre.code .object_link a { - padding: 0px; background: inherit; color: inherit; border-radius: inherit; + display: block; + height: 20px; + border: 1px solid #aaa; + border-bottom: 0; + border-top-left-radius: 5px; + background: #f8f8f8; + position: relative; + padding: 2px 7px; +} +.clear { + clear: both; +} +.inline { + display: inline; +} +.inline p:first-child { + display: inline; +} +.docstring, +.tags, +#filecontents { + font-size: 15px; + line-height: 1.5145em; +} +*:not(pre) > code { + padding: 1px 3px 1px 3px; + border: 1px solid #e1e1e8; + background: #f7f7f9; + border-radius: 4px; +} +.summary_desc tt { + font-size: 0.9em; +} +.docstring p > code, +.docstring p > tt, +.tags p > code, +.tags p > tt { + color: #c7254e; + background: #f9f2f4; + padding: 2px 4px; + font-size: 1em; + border-radius: 4px; +} +.docstring h1, +.docstring h2, +.docstring h3, +.docstring h4 { + padding: 0; + border: 0; + border-bottom: 1px dotted #bbb; +} +.docstring h1 { + font-size: 1.2em; +} +.docstring h2 { + font-size: 1.1em; +} +.docstring h3, +.docstring h4 { + font-size: 1em; + border-bottom: 0; + padding-top: 10px; +} +.summary_desc .object_link a, +.docstring .object_link a { + font-family: monospace; + color: #05a; + background: #edf4fa; + padding: 2px 4px; + font-size: 1em; + border-radius: 4px; +} +.rdoc-term { + padding-right: 25px; + font-weight: bold; +} +.rdoc-list p { + margin: 0; + padding: 0; + margin-bottom: 4px; +} +.summary_desc pre.code .object_link a, +.docstring pre.code .object_link a { + padding: 0px; + background: inherit; + color: inherit; + border-radius: inherit; } /* style for */ -#filecontents table, .docstring table { border-collapse: collapse; } -#filecontents table th, #filecontents table td, -.docstring table th, .docstring table td { border: 1px solid #ccc; padding: 8px; padding-right: 17px; } -#filecontents table tr:nth-child(odd), -.docstring table tr:nth-child(odd) { background: #eee; } -#filecontents table tr:nth-child(even), -.docstring table tr:nth-child(even) { background: #fff; } -#filecontents table th, .docstring table th { background: #fff; } - -/* style for
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Tokens to Remember +Gem name Gem namespace +
Works with JRuby +JRuby 9.1 Compat JRuby 9.2 Compat JRuby 9.3 Compat
JRuby 9.4 Compat JRuby 10.0 Compat JRuby HEAD Compat +
Works with Truffle Ruby +Truffle Ruby 22.3 Compat Truffle Ruby 23.0 Compat Truffle Ruby 23.1 Compat
Truffle Ruby 24.1 Compat +
Works with MRI Ruby 3 +Ruby 3.0 Compat Ruby 3.1 Compat Ruby 3.2 Compat Ruby 3.3 Compat Ruby 3.4 Compat Ruby HEAD Compat +
Works with MRI Ruby 2 +Ruby 2.2 Compat
Ruby 2.3 Compat Ruby 2.4 Compat Ruby 2.5 Compat Ruby 2.6 Compat Ruby 2.7 Compat +
Support & Community +Join Me on Daily.dev's RubyFriends Live Chat on Discord Get help from me on Upwork Get help from me on Codementor +
Source +Source on GitLab.com Source on CodeBerg.org Source on Github.com The best SHA: dQw4w9WgXcQ! +
Documentation +Current release on RubyDoc.info YARD on Galtzo.com Maintainer Blog GitLab Wiki GitHub Wiki +
Compliance +License: MIT Compatible with Apache Software Projects: Verified by SkyWalking Eyes 📄ilo-declaration-img Security Policy Contributor Covenant 2.1 SemVer 2.0.0 +
Style +Enforced Code Style Linter Keep-A-Changelog 1.0.0 Gitmoji Commits Compatibility appraised by: appraisal2 +
Maintainer 🎖️ +Follow Me on LinkedIn Follow Me on Ruby.Social Follow Me on Bluesky Contact Maintainer My technical writing +
+... 💖 +Find Me on WellFound: Find Me on CrunchBase My LinkTree More About Me 🧊 🐙 🛖 🧪 +
+ +

Compatibility

+ +

Compatible with MRI Ruby 2.2.0+, and concordant releases of JRuby, and TruffleRuby.

+ + + + + + + + + + + + + + +
🚚 Amazing test matrix was brought to you by🔎 appraisal2 🔎 and the color 💚 green 💚
👟 Check it out!github.com/appraisal-rb/appraisal2
+ +

Federated DVCS

+ +
+ Find this repo on federated forges (Coming soon!) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Federated DVCS RepositoryStatusIssuesPRsWikiCIDiscussions
🧪 ruby-oauth/oauth2 on GitLab +The Truth💚💚💚🐭 Tiny Matrix
🧊 ruby-oauth/oauth2 on CodeBerg +An Ethical Mirror (Donate)💚💚⭕️ No Matrix
🐙 ruby-oauth/oauth2 on GitHub +Another Mirror💚💚💚💯 Full Matrix💚
🎮️ Discord Server +Live Chat on DiscordLet’stalkaboutthislibrary!
+ +
+ +

Enterprise Support Tidelift +

+ +

Available as part of the Tidelift Subscription.

+ +
+ Need enterprise-level guarantees? + +

The maintainers of this and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use.

+ +

Get help from me on Tidelift

+ + + +

Alternatively:

+ + + +
+ +

✨ Installation

+ +

Install the gem and add to the application’s Gemfile by executing:

+ +
bundle add oauth2
+
+ +

If bundler is not being used to manage dependencies, install the gem by executing:

+ +
gem install oauth2
+
+ +

🔒 Secure Installation

+ +
+ For Medium or High Security Installations + +

This gem is cryptographically signed, and has verifiable SHA-256 and SHA-512 checksums by +stone_checksums. Be sure the gem you install hasn’t been tampered with +by following the instructions below.

+ +

Add my public key (if you haven’t already, expires 2045-04-29) as a trusted certificate:

+ +
gem cert --add <(curl -Ls https://raw.github.com/galtzo-floss/certs/main/pboling.pem)
+
+ +

You only need to do that once. Then proceed to install with:

+ +
gem install oauth2 -P MediumSecurity
+
+ +

The MediumSecurity trust profile will verify signed gems, but allow the installation of unsigned dependencies.

+ +

This is necessary because not all of oauth2’s dependencies are signed, so we cannot use HighSecurity.

+ +

If you want to up your security game full-time:

+ +
bundle config set --global trust-policy MediumSecurity
+
+ +

MediumSecurity instead of HighSecurity is necessary if not all the gems you use are signed.

+ +

NOTE: Be prepared to track down certs for signed gems and add them the same way you added mine.

+ +
+ +

What is new for v2.0?

+ + + +

Compatibility

+ +

Targeted ruby compatibility is non-EOL versions of Ruby, currently 3.2, 3.3, and 3.4.
+Compatibility is further distinguished as “Best Effort Support” or “Incidental Support” for older versions of Ruby.
+This gem will install on Ruby versions >= v2.2 for 2.x releases.
+See 1-4-stable branch for older rubies.

+ +
+ Ruby Engine Compatibility Policy + +

This gem is tested against MRI, JRuby, and Truffleruby. +Each of those has varying versions that target a specific version of MRI Ruby. +This gem should work in the just-listed Ruby engines according to the targeted MRI compatibility in the table below. +If you would like to add support for additional engines, +see gemfiles/README.md, then submit a PR to the correct maintenance branch as according to the table below.

+ +
+ +
+ Ruby Version Compatibility Policy + +

If something doesn’t work on one of these interpreters, it’s a bug.

+ +

This library may inadvertently work (or seem to work) on other Ruby +implementations; however, support will only be provided for the versions listed +above.

+ +

If you would like this library to support another Ruby version, you may +volunteer to be a maintainer. Being a maintainer entails making sure all tests +run and pass on that implementation. When something breaks on your +implementation, you will be responsible for providing patches in a timely +fashion. If critical issues for a particular implementation exist at the time +of a major release, support for that Ruby version may be dropped.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 Ruby OAuth2 VersionMaintenance BranchTargeted SupportBest Effort SupportIncidental Support
1️⃣2.0.xmain3.2, 3.3, 3.42.5, 2.6, 2.7, 3.0, 3.12.2, 2.3, 2.4
2️⃣1.4.x1-4-stable3.2, 3.3, 3.42.5, 2.6, 2.7, 3.0, 3.11.9, 2.0, 2.1, 2.2, 2.3, 2.4
3️⃣olderN/ABest of luck to you!Please upgrade! 
+ +

NOTE: The 1.4 series will only receive critical security updates.
+See SECURITY.md and IRP.md.

+ +

⚙️ Configuration

+ +

Global settings for the library:

+ +
OAuth2.configure do |config|
+  config.silence_extra_tokens_warning = false # default: true
+  config.silence_no_tokens_warning = false    # default: true
+end
+
+ +

Filtering-related settings:

+ +
OAuth2.configure do |config|
+  config.filtered_label = "[REDACTED]" # default: "[FILTERED]"
+  config.filtered_debug_keys += ["client_assertion"]
+end
+
+ + + +

🔧 Basic Usage

+ +

Client Initialization Options

+ +

OAuth2::Client.new accepts several options:

+ + + +
+ authorize_url and token_url + +

+authorize_url and token_url are on site root (Just Works!)

+ +
require "oauth2"
+client = OAuth2::Client.new("client_id", "client_secret", site: "https://example.org")
+# => #<OAuth2::Client:0x00000001204c8288 @id="client_id", @secret="client_sec...
+client.auth_code.authorize_url(redirect_uri: "http://localhost:8080/oauth2/callback")
+# => "https://example.org/oauth/authorize?client_id=client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&response_type=code"
+
+access = client.auth_code.get_token("authorization_code_value", redirect_uri: "http://localhost:8080/oauth2/callback", headers: {"Authorization" => "Basic some_password"})
+response = access.get("/api/resource", params: {"query_foo" => "bar"})
+response.class.name
+# => OAuth2::Response
+
+ +

Relative authorize_url and token_url (Not on site root, Just Works!)

+ +

In the above example, the default Authorization URL is oauth/authorize and default Access Token URL is oauth/token, and, as they are missing a leading /, both are relative.

+ +
client = OAuth2::Client.new("client_id", "client_secret", site: "https://example.org/nested/directory/on/your/server")
+# => #<OAuth2::Client:0x00000001204c8288 @id="client_id", @secret="client_sec...
+client.auth_code.authorize_url(redirect_uri: "http://localhost:8080/oauth2/callback")
+# => "https://example.org/nested/directory/on/your/server/oauth/authorize?client_id=client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&response_type=code"
+
+ +

Customize authorize_url and token_url +

+ +

You can specify custom URLs for authorization and access token, and when using a leading / they will not be relative, as shown below:

+ +
client = OAuth2::Client.new(
+  "client_id",
+  "client_secret",
+  site: "https://example.org/nested/directory/on/your/server",
+  authorize_url: "/jaunty/authorize/",
+  token_url: "/stirrups/access_token",
+)
+# => #<OAuth2::Client:0x00000001204c8288 @id="client_id", @secret="client_sec...
+client.auth_code.authorize_url(redirect_uri: "http://localhost:8080/oauth2/callback")
+# => "https://example.org/jaunty/authorize/?client_id=client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&response_type=code"
+client.class.name
+# => OAuth2::Client
+
+ +
+ +

Advanced Initializers

+ +
client = OAuth2::Client.new(id, secret, site: site) do |faraday|
+  faraday.request(:url_encoded)
+  faraday.adapter(:net_http_persistent)
+end
+
+ +

AccessToken Features

+ +

Instances of OAuth2::AccessToken handle request signing and token expiration.

+ + + +

snake_case and indifferent access in Response#parsed

+ +
response = access.get("/api/resource", params: {"query_foo" => "bar"})
+# Even if the actual response is CamelCase. it will be made available as snaky:
+JSON.parse(response.body)         # => {"accessToken"=>"aaaaaaaa", "additionalData"=>"additional"}
+response.parsed                   # => {"access_token"=>"aaaaaaaa", "additional_data"=>"additional"}
+response.parsed.access_token      # => "aaaaaaaa"
+response.parsed[:access_token]    # => "aaaaaaaa"
+response.parsed.additional_data   # => "additional"
+response.parsed[:additional_data] # => "additional"
+response.parsed.class.name        # => SnakyHash::StringKeyed (from snaky_hash gem)
+
+ +

Serialization

+ +

As of v2.0.11, if you need to serialize the parsed result, you can!

+ +

There are two ways to do this, globally, or discretely. The discrete way is recommended.

+ +
Global Serialization Config
+ +

Globally configure SnakyHash::StringKeyed to use the serializer. Put this in your code somewhere reasonable (like an initializer for Rails).

+ +
SnakyHash::StringKeyed.class_eval do
+  extend SnakyHash::Serializer
+end
+
+ +
Discrete Serialization Config
+ +

Discretely configure a custom Snaky Hash class to use the serializer.

+ +
class MySnakyHash < SnakyHash::StringKeyed
+  # Give this hash class `dump` and `load` abilities!
+  extend SnakyHash::Serializer
+end
+
+# And tell your client to use the custom class in each call:
+client = OAuth2::Client.new("client_id", "client_secret", site: "https://example.org/oauth2")
+token = client.get_token({snaky_hash_klass: MySnakyHash})
+
+ +
Serialization Extensions
+ +

These extensions work regardless of whether you used the global or discrete config above.

+ +

There are a few hacks you may need in your class to support Ruby < 2.4.2 or < 2.6.
+They are likely not needed if you are on a newer Ruby.
+Expand the examples below, or the ruby-oauth/snaky_hash gem,
+or response_spec.rb, for more ideas, especially if you need to study the hacks for older Rubies.

+ +
+ See Examples + +
class MySnakyHash < SnakyHash::StringKeyed
+  # Give this hash class `dump` and `load` abilities!
+  extend SnakyHash::Serializer
+
+  #### Serialization Extentions
+  #
+  # Act on the non-hash values (including the values of hashes) as they are dumped to JSON
+  # In other words, this retains nested hashes, and only the deepest leaf nodes become bananas.
+  # WARNING: This is a silly example!
+  dump_value_extensions.add(:to_fruit) do |value|
+    "banana" # => Make values "banana" on dump
+  end
+
+  # Act on the non-hash values (including the values of hashes) as they are loaded from the JSON dump
+  # In other words, this retains nested hashes, and only the deepest leaf nodes become ***.
+  # WARNING: This is a silly example!
+  load_value_extensions.add(:to_stars) do |value|
+    "***" # Turn dumped bananas into *** when they are loaded
+  end
+
+  # Act on the entire hash as it is prepared for dumping to JSON
+  # WARNING: This is a silly example!
+  dump_hash_extensions.add(:to_cheese) do |value|
+    if value.is_a?(Hash)
+      value.transform_keys do |key|
+        split = key.split("_")
+        first_word = split[0]
+        key.sub(first_word, "cheese")
+      end
+    else
+      value
+    end
+  end
+
+  # Act on the entire hash as it is loaded from the JSON dump
+  # WARNING: This is a silly example!
+  load_hash_extensions.add(:to_pizza) do |value|
+    if value.is_a?(Hash)
+      res = klass.new
+      value.keys.each_with_object(res) do |key, result|
+        split = key.split("_")
+        last_word = split[-1]
+        new_key = key.sub(last_word, "pizza")
+        result[new_key] = value[key]
+      end
+      res
+    else
+      value
+    end
+  end
+end
+
+ +
+ +

Prefer camelCase over snake_case? => snaky: false

+ +
response = access.get("/api/resource", params: {"query_foo" => "bar"}, snaky: false)
+JSON.parse(response.body)         # => {"accessToken"=>"aaaaaaaa", "additionalData"=>"additional"}
+response.parsed                   # => {"accessToken"=>"aaaaaaaa", "additionalData"=>"additional"}
+response.parsed["accessToken"]    # => "aaaaaaaa"
+response.parsed["additionalData"] # => "additional"
+response.parsed.class.name        # => Hash (just, regular old Hash)
+
+ +
+ Debugging & Logging + +

Set an environment variable as per usual (e.g. with dotenv).

+ +
# will log both request and response, including bodies
+ENV["OAUTH_DEBUG"] = "true"
+
+ +

By default, debug output will go to $stdout. This can be overridden when +initializing your OAuth2::Client.

+ +

Sensitive values are filtered from debug logging output using:

+ + + +

Debug logging remains opt-in and should still be used cautiously in production environments.

+ +
require "oauth2"
+client = OAuth2::Client.new(
+  "client_id",
+  "client_secret",
+  site: "https://example.org",
+  logger: Logger.new("example.log", "weekly"),
+)
+
+ +
+ +

Request Target Trust Boundaries

+ +

This gem supports request flows that can involve absolute URLs in addition to relative paths.
+That flexibility can expand trust boundaries when a token-bearing client is asked to send requests
+to caller-provided targets.

+ +

Practical guidance:

+ + + +

This release line does not yet enforce same-host or allowlist request policy automatically.
+If stricter outbound request controls are needed, they should currently be implemented by the calling application.

+ +

OAuth2::Response

+ +

The AccessToken methods #get, #post, #put and #delete and the generic #request
+will return an instance of the OAuth2::Response class.

+ +

This instance contains a #parsed method that will parse the response body and
+return a Hash-like SnakyHash::StringKeyed if the Content-Type is application/x-www-form-urlencoded or if
+the body is a JSON object. It will return an Array if the body is a JSON
+array. Otherwise, it will return the original body string.

+ +

The original response body, headers, and status can be accessed via their
+respective methods.

+ +

OAuth2::AccessToken

+ +

If you have an existing Access Token for a user, you can initialize an instance
+using various class methods including the standard new, from_hash (if you have
+a hash of the values), or from_kvform (if you have an
+application/x-www-form-urlencoded encoded string of the values).

+ +

Options (since v2.0.x unless noted):

+ + + +

Note: Verb-dependent mode supports providers like Instagram that require query mode for GET and header mode for POST/DELETE

+ + + +

OAuth2::Error

+ +

On 400+ status code responses, an OAuth2::Error will be raised. If it is a
+standard OAuth2 error response, the body will be parsed and #code and #description will contain the values provided from the error and
+error_description parameters. The #response property of OAuth2::Error will
+always contain the OAuth2::Response instance.

+ +

If you do not want an error to be raised, you may use :raise_errors => false
+option on initialization of the client. In this case the OAuth2::Response
+instance will be returned as usual and on 400+ status code responses, the
+Response instance will contain the OAuth2::Error instance.

+ +

Authorization Grants

+ +

Currently, the Authorization Code, Implicit, Resource Owner Password Credentials, Client Credentials, and Assertion
+authentication grant types have helper strategy classes that simplify client
+use. They are available via the #auth_code,
+#implicit,
+#password,
+#client_credentials, and
+#assertion methods respectively.

+ +

OAuth 2.1 (draft) Note:

+ + + +
+ OAuth 2.1 (draft) References + + + +
+ +

These aren’t full examples, but demonstrative of the differences between usage for each strategy.

+ +
auth_url = client.auth_code.authorize_url(redirect_uri: "http://localhost:8080/oauth/callback")
+access = client.auth_code.get_token("code_value", redirect_uri: "http://localhost:8080/oauth/callback")
+
+auth_url = client.implicit.authorize_url(redirect_uri: "http://localhost:8080/oauth/callback")
+# get the token params in the callback and
+access = OAuth2::AccessToken.from_kvform(client, query_string)
+
+access = client.password.get_token("username", "password")
+
+access = client.client_credentials.get_token
+
+# Client Assertion Strategy
+# see: https://tools.ietf.org/html/rfc7523
+claimset = {
+  iss: "http://localhost:3001",
+  aud: "http://localhost:8080/oauth2/token",
+  sub: "me@example.com",
+  exp: Time.now.utc.to_i + 3600,
+}
+assertion_params = [claimset, "HS256", "secret_key"]
+access = client.assertion.get_token(assertion_params)
+
+# The `access` (i.e. access token) is then used like so:
+access.token # actual access_token string, if you need it somewhere
+access.get("/api/stuff") # making api calls with access token
+
+ +

If you want to specify additional headers to be sent out with the
+request, add a ‘headers’ hash under ‘params’:

+ +
access = client.auth_code.get_token("code_value", redirect_uri: "http://localhost:8080/oauth/callback", headers: {"Some" => "Header"})
+
+ +

You can always use the #request method on the OAuth2::Client instance to make
+requests for tokens for any Authentication grant type.

+ +

📘 Comprehensive Usage

+ +

Common Flows (end-to-end)

+ + + +
require "oauth2"
+client = OAuth2::Client.new(
+  ENV["CLIENT_ID"],
+  ENV["CLIENT_SECRET"],
+  site: "https://provider.example.com",
+  redirect_uri: "https://my.app.example.com/oauth/callback",
+)
+
+# Step 1: redirect user to consent
+state = SecureRandom.hex(16)
+auth_url = client.auth_code.authorize_url(scope: "openid profile email", state: state)
+# redirect_to auth_url
+
+# Step 2: handle the callback
+# params[:code], params[:state]
+raise "state mismatch" unless params[:state] == state
+access = client.auth_code.get_token(params[:code])
+
+# Step 3: call APIs
+profile = access.get("/api/v1/me").parsed
+
+ + + +
client = OAuth2::Client.new(ENV["CLIENT_ID"], ENV["CLIENT_SECRET"], site: "https://provider.example.com")
+access = client.client_credentials.get_token(audience: "https://api.example.com")
+resp = access.get("/v1/things")
+
+ + + +
access = client.password.get_token("jdoe", "s3cret", scope: "read")
+
+ +

Examples

+ +
+ JHipster UAA (Spring Cloud) password grant example (legacy; avoid when possible) + +
# This converts a Postman/Net::HTTP multipart token request to oauth2 gem usage.
+# JHipster UAA typically exposes the token endpoint at /uaa/oauth/token.
+# The original snippet included:
+# - Basic Authorization header for the client (web_app:changeit)
+# - X-XSRF-TOKEN header from a cookie (some deployments require it)
+# - grant_type=password with username/password and client_id
+# Using oauth2 gem, you don't need to build multipart bodies; the gem sends
+# application/x-www-form-urlencoded as required by RFC 6749.
+
+require "oauth2"
+
+client = OAuth2::Client.new(
+  "web_app",            # client_id
+  "changeit",           # client_secret
+  site: "http://localhost:8080/uaa",
+  token_url: "/oauth/token",      # absolute under site (or "oauth/token" relative)
+  auth_scheme: :basic_auth,         # sends HTTP Basic Authorization header
+)
+
+# If your UAA requires an XSRF header for the token call, provide it as a header.
+# Often this is not required for token endpoints, but if your gateway enforces it,
+# obtain the value from the XSRF-TOKEN cookie and pass it here.
+xsrf_token = ENV["X_XSRF_TOKEN"] # e.g., pulled from a prior set-cookie value
+
+access = client.password.get_token(
+  "admin",                 # username
+  "admin",                 # password
+  headers: xsrf_token ? {"X-XSRF-TOKEN" => xsrf_token} : {},
+  # JHipster commonly also accepts/needs the client_id in the body; include if required:
+  # client_id: "web_app",
+)
+
+puts access.token
+puts access.to_hash # full token response
+
+ +

Notes:

+ + + +
+ +

Verb‑dependent Token Mode

+ +

Providers like Instagram require the access token to be sent differently depending on the HTTP verb:

+ + + +

Since v2.0.15, you can configure an AccessToken with a verb‑dependent mode. The gem will choose how to send the token based on the request method.

+ +

Tips:

+ + + +
+ Instagram API Example + +

Example: exchanging and refreshing long‑lived Instagram tokens, and making API calls

+ +
require "oauth2"
+
+# NOTE: Users authenticate via Facebook Login to obtain a short‑lived user token (not shown here).
+# See Facebook Login docs for obtaining the initial short‑lived token.
+
+client = OAuth2::Client.new(nil, nil, site: "https://graph.instagram.com")
+
+# Start with a short‑lived token you already obtained via Facebook Login
+short_lived = OAuth2::AccessToken.new(
+  client,
+  ENV["IG_SHORT_LIVED_TOKEN"],
+  # Key part: verb‑dependent mode
+  mode: {get: :query, post: :header, delete: :header},
+)
+
+# 1) Exchange for a long‑lived token (Instagram requires GET with access_token in query)
+#    Endpoint: GET https://graph.instagram.com/access_token
+#    Params: grant_type=ig_exchange_token, client_secret=APP_SECRET
+exchange = short_lived.get(
+  "/access_token",
+  params: {
+    grant_type: "ig_exchange_token",
+    client_secret: ENV["IG_APP_SECRET"],
+    # access_token param will be added automatically by the AccessToken (mode => :query for GET)
+  },
+)
+long_lived_token_value = exchange.parsed["access_token"]
+
+long_lived = OAuth2::AccessToken.new(
+  client,
+  long_lived_token_value,
+  mode: {get: :query, post: :header, delete: :header},
+)
+
+# 2) Refresh the long‑lived token (Instagram uses GET with token in query)
+#    Endpoint: GET https://graph.instagram.com/refresh_access_token
+refresh_resp = long_lived.get(
+  "/refresh_access_token",
+  params: {grant_type: "ig_refresh_token"},
+)
+long_lived = OAuth2::AccessToken.new(
+  client,
+  refresh_resp.parsed["access_token"],
+  mode: {get: :query, post: :header, delete: :header},
+)
+
+# 3) Typical API GET request (token in query automatically)
+me = long_lived.get("/me", params: {fields: "id,username"}).parsed
+
+# 4) Example POST (token sent via Bearer header automatically)
+# Note: Replace the path/params with a real Instagram Graph API POST you need,
+# such as publishing media via the Graph API endpoints.
+# long_lived.post("/me/media", body: {image_url: "https://...", caption: "hello"})
+
+ +
+ +

Refresh Tokens

+ +

When the server issues a refresh_token, you can refresh manually or implement an auto-refresh wrapper.

+ + + +
if access.expired?
+  access = access.refresh
+end
+
+ + + +
class AutoRefreshingToken
+  def initialize(token_provider, store: nil)
+    @token = token_provider
+    @store = store # e.g., something that responds to read/write for token data
+  end
+
+  def with(&blk)
+    tok = ensure_fresh!
+    blk ? blk.call(tok) : tok
+  rescue OAuth2::Error => e
+    # If a 401 suggests token invalidation, try one refresh and retry once
+    if e.response && e.response.status == 401 && @token.refresh_token
+      @token = @token.refresh
+      @store.write(@token.to_hash) if @store
+      retry
+    end
+    raise
+  end
+
+private
+
+  def ensure_fresh!
+    if @token.expired? && @token.refresh_token
+      @token = @token.refresh
+      @store.write(@token.to_hash) if @store
+    end
+    @token
+  end
+end
+
+# usage
+keeper = AutoRefreshingToken.new(access)
+keeper.with { |tok| tok.get("/v1/protected") }
+
+ +

Persist the token across processes using AccessToken#to_hash and AccessToken.from_hash(client, hash).

+ +

Token Revocation (RFC 7009)

+ +

You can revoke either the access token or the refresh token.

+ +
# Revoke the current access token
+access.revoke(token_type_hint: :access_token)
+
+# Or explicitly revoke the refresh token (often also invalidates associated access tokens)
+access.revoke(token_type_hint: :refresh_token)
+
+ +

Client Configuration Tips

+ +

Mutual TLS (mTLS) client authentication

+ +

Some providers require OAuth requests (including the token request and subsequent API calls) to be sender‑constrained using mutual TLS (mTLS). With this gem, you enable mTLS by providing a client certificate/private key to Faraday via connection_opts.ssl and, if your provider requires it for client authentication, selecting the tls_client_auth auth_scheme.

+ +

Example using PEM files (certificate and key):

+ +
require "oauth2"
+require "openssl"
+
+client = OAuth2::Client.new(
+  ENV.fetch("CLIENT_ID"),
+  ENV.fetch("CLIENT_SECRET"),
+  site: "https://example.com",
+  authorize_url: "/oauth/authorize/",
+  token_url: "/oauth/token/",
+  auth_scheme: :tls_client_auth, # if your AS requires mTLS-based client authentication
+  connection_opts: {
+    ssl: {
+      client_cert: OpenSSL::X509::Certificate.new(File.read("localhost.pem")),
+      client_key: OpenSSL::PKey::RSA.new(File.read("localhost-key.pem")),
+      # Optional extras, uncomment as needed:
+      # ca_file: "/path/to/ca-bundle.pem",   # custom CA(s)
+      # verify: true                           # enable server cert verification (recommended)
+    },
+  },
+)
+
+# Example token request (any grant type can be used). The mTLS handshake
+# will occur automatically on HTTPS calls using the configured cert/key.
+access = client.client_credentials.get_token
+
+# Subsequent resource requests will also use mTLS on HTTPS endpoints of `site`:
+resp = access.get("/v1/protected")
+
+ +

Notes:

+ + + +

Authentication schemes for the token request

+ +
OAuth2::Client.new(
+  id,
+  secret,
+  site: "https://provider.example.com",
+  auth_scheme: :basic_auth, # default. Alternatives: :request_body, :tls_client_auth, :private_key_jwt
+)
+
+ +

Faraday connection, timeouts, proxy, custom adapter/middleware:

+ +
client = OAuth2::Client.new(
+  id,
+  secret,
+  site: "https://provider.example.com",
+  connection_opts: {
+    request: {open_timeout: 5, timeout: 15},
+    proxy: ENV["HTTPS_PROXY"],
+    ssl: {verify: true},
+  },
+) do |faraday|
+  faraday.request(:url_encoded)
+  # faraday.response :logger, Logger.new($stdout) # see OAUTH_DEBUG below
+  faraday.adapter(:net_http_persistent) # or any Faraday adapter you need
+end
+
+ +
Using flat query params (Faraday::FlatParamsEncoder)
+ +

Some APIs expect repeated key parameters to be sent as flat params rather than arrays. Faraday provides FlatParamsEncoder for this purpose. You can configure the oauth2 client to use it when building requests.

+ +
require "faraday"
+
+client = OAuth2::Client.new(
+  id,
+  secret,
+  site: "https://api.example.com",
+  # Pass Faraday connection options to make FlatParamsEncoder the default
+  connection_opts: {
+    request: {params_encoder: Faraday::FlatParamsEncoder},
+  },
+) do |faraday|
+  faraday.request(:url_encoded)
+  faraday.adapter(:net_http)
+end
+
+access = client.client_credentials.get_token
+
+# Example of a GET with two flat filter params (not an array):
+# Results in: ?filter=order.clientCreatedTime%3E1445006997000&filter=order.clientCreatedTime%3C1445611797000
+resp = access.get(
+  "/v1/orders",
+  params: {
+    # Provide the values as an array; FlatParamsEncoder expands them as repeated keys
+    filter: [
+      "order.clientCreatedTime>1445006997000",
+      "order.clientCreatedTime<1445611797000",
+    ],
+  },
+)
+
+ +

If you instead need to build a raw Faraday connection yourself, the equivalent configuration is:

+ +
conn = Faraday.new("https://api.example.com", request: {params_encoder: Faraday::FlatParamsEncoder})
+
+ +

Redirection

+ +

The library follows up to max_redirects (default 5).
+You can override per-client via options[:max_redirects].

+ +

Handling Responses and Errors

+ + + +
resp = access.get("/v1/thing")
+resp.status     # Integer
+resp.headers    # Hash
+resp.body       # String
+resp.parsed     # SnakyHash::StringKeyed or Array when JSON array
+
+ + + +
begin
+  access.get("/v1/forbidden")
+rescue OAuth2::Error => e
+  e.code         # OAuth2 error code (when present)
+  e.description  # OAuth2 error description (when present)
+  e.response     # OAuth2::Response (full access to status/headers/body)
+end
+
+ + + +
client = OAuth2::Client.new(id, secret, site: site, raise_errors: false)
+res = client.request(:get, "/v1/maybe-errors")
+if res.status == 429
+  sleep res.headers["retry-after"].to_i
+end
+
+ +

Making Raw Token Requests

+ +

If a provider requires non-standard parameters or headers, you can call client.get_token directly:

+ +
access = client.get_token({
+  grant_type: "client_credentials",
+  audience: "https://api.example.com",
+  headers: {"X-Custom" => "value"},
+  parse: :json, # override parsing
+})
+
+ +

OpenID Connect (OIDC)

+ + + +

Debugging

+ + + +
+ +

🦷 FLOSS Funding

+ +

While ruby-oauth tools are free software and will always be, the project would benefit immensely from some funding.
+Raising a monthly budget of… “dollars” would make the project more sustainable.

+ +

We welcome both individual and corporate sponsors! We also offer a
+wide array of funding channels to account for your preferences
+(although currently Open Collective is our preferred funding platform).

+ +

If you’re working in a company that’s making significant use of ruby-oauth tools we’d
+appreciate it if you suggest to your company to become a ruby-oauth sponsor.

+ +

You can support the development of ruby-oauth tools via
+GitHub Sponsors,
+Liberapay,
+PayPal,
+Open Collective
+and Tidelift.

+ + + + + + + + + + + + +
📍 NOTE
If doing a sponsorship in the form of donation is problematic for your company
from an accounting standpoint, we’d recommend the use of Tidelift,
where you can get a support-like subscription instead.
+ +

Open Collective for Individuals

+ +

Support us with a monthly donation and help us continue our activities. [Become a backer]

+ +

NOTE: kettle-readme-backers updates this list every day, automatically.

+ + +

No backers yet. Be the first!
+

+ +

Open Collective for Organizations

+ +

Become a sponsor and get your logo on our README on GitHub with a link to your site. [Become a sponsor]

+ +

NOTE: kettle-readme-backers updates this list every day, automatically.

+ + +

No sponsors yet. Be the first!

+ +

Open Collective for Donors

+ +

Bill Woika
+

+ +

Another way to support open-source

+ +

I’m driven by a passion to foster a thriving open-source community – a space where people can tackle complex problems, no matter how small. Revitalizing libraries that have fallen into disrepair, and building new libraries focused on solving real-world challenges, are my passions. I was recently affected by layoffs, and the tech jobs market is unwelcoming. I’m reaching out here because your support would significantly aid my efforts to provide for my family, and my farm (11 🐔 chickens, 2 🐶 dogs, 3 🐰 rabbits, 8 🐈‍ cats).

+ +

If you work at a company that uses my work, please encourage them to support me as a corporate sponsor. My work on gems you use might show up in bundle fund.

+ +

I’m developing a new library, floss_funding, designed to empower open-source developers like myself to get paid for the work we do, in a sustainable way. Please give it a look.

+ +

Floss-Funding.dev: 👉️ No network calls. 👉️ No tracking. 👉️ No oversight. 👉️ Minimal crypto hashing. 💡 Easily disabled nags

+ +

OpenCollective Backers OpenCollective Sponsors Sponsor Me on Github Liberapay Goal Progress Donate on PayPal Buy me a coffee Donate on Polar Donate to my FLOSS efforts at ko-fi.com Donate to my FLOSS efforts using Patreon

+ +

🔐 Security

+ +

To report a security vulnerability, please use the Tidelift security contact.
+Tidelift will coordinate the fix and disclosure.

+ +

For more see SECURITY.md, THREAT_MODEL.md, and IRP.md.

+ +

🤝 Contributing

+ +

If you need some ideas of where to help, you could work on adding more code coverage,
+or if it is already 💯 (see below) check reek, issues, or PRs,
+or use the gem and think about how it could be better.

+ +

We Keep A Changelog so if you make changes, remember to update it.

+ +

See CONTRIBUTING.md for more detailed instructions.

+ +

🚀 Release Instructions

+ +

See CONTRIBUTING.md.

+ +

Code Coverage

+ +

Coverage Graph

+ +

Coveralls Test Coverage

+ +

QLTY Test Coverage

+ +

🪇 Code of Conduct

+ +

Everyone interacting with this project’s codebases, issue trackers,
+chat rooms and mailing lists agrees to follow the Contributor Covenant 2.1.

+ +

🌈 Contributors

+ +

Contributors

+ +

Made with contributors-img.

+ +

Also see GitLab Contributors: https://gitlab.com/ruby-oauth/oauth2/-/graphs/main

+ +
+ ⭐️ Star History + + + + + + Star History Chart + + + +
+ +

📌 Versioning

+ +

This Library adheres to Semantic Versioning 2.0.0.
+Violations of this scheme should be reported as bugs.
+Specifically, if a minor or patch version is released that breaks backward compatibility,
+a new version should be immediately released that restores compatibility.
+Breaking changes to the public API will only be introduced with new major versions.

+ +
+

dropping support for a platform is both obviously and objectively a breaking change

+—Jordan Harband (@ljharb, maintainer of SemVer) in SemVer issue 716

+
+ +

I understand that policy doesn’t work universally (“exceptions to every rule!”),
+but it is the policy here.
+As such, in many cases it is good to specify a dependency on this library using
+the Pessimistic Version Constraint with two digits of precision.

+ +

For example:

+ +
spec.add_dependency("oauth2", "~> 2.0")
+
+ +
+ 📌 Is "Platform Support" part of the public API? More details inside. + +

SemVer should, IMO, but doesn’t explicitly, say that dropping support for specific Platforms +is a breaking change to an API, and for that reason the bike shedding is endless.

+ +

To get a better understanding of how SemVer is intended to work over a project’s lifetime, +read this article from the creator of SemVer:

+ + + +
+ +

See CHANGELOG.md for a list of releases.

+ +

📄 License

+ +

The gem is available as open source under the terms of
+the MIT License License: MIT.
+See LICENSE.txt for the official Copyright Notice.

+ + + + + +

🤑 A request for help

+ +

Maintainers have teeth and need to pay their dentists.
+After getting laid off in an RIF in March, and encountering difficulty finding a new one,
+I began spending most of my time building open source tools.
+I’m hoping to be able to pay for my kids’ health insurance this month,
+so if you value the work I am doing, I need your support.
+Please consider sponsoring me or the project.

+ +

To join the community or get help 👇️ Join the Discord.

+ +

Live Chat on Discord

+ +

To say “thanks!” ☝️ Join the Discord or 👇️ send money.

+ +

Sponsor ruby-oauth/oauth2 on Open Source Collective 💌 Sponsor me on GitHub Sponsors 💌 Sponsor me on Liberapay 💌 Donate on PayPal

+ +

Please give the project a star ⭐ ♥.

+ +

Thanks for RTFM. ☺️

+ +
+ + rel="me" Social Proofs + + + + + +
+ + + + + + + diff --git a/docs/file.REEK.html b/docs/file.REEK.html index e69de29bb..ca6db01f0 100644 --- a/docs/file.REEK.html +++ b/docs/file.REEK.html @@ -0,0 +1,74 @@ + + + + + + + File: REEK + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Error: No such file - is
+Error: No such file - empty

+
+ + + +
+ + diff --git a/docs/file.RUBOCOP.html b/docs/file.RUBOCOP.html index e69de29bb..a40551e31 100644 --- a/docs/file.RUBOCOP.html +++ b/docs/file.RUBOCOP.html @@ -0,0 +1,173 @@ + + + + + + + File: RUBOCOP + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

RuboCop Usage Guide

+ +

Overview

+ +

A tale of two RuboCop plugin gems.

+ +

RuboCop Gradual

+ +

This project uses rubocop_gradual instead of vanilla RuboCop for code style checking. The rubocop_gradual tool allows for gradual adoption of RuboCop rules by tracking violations in a lock file.

+ +

RuboCop LTS

+ +

This project uses rubocop-lts to ensure, on a best-effort basis, compatibility with Ruby >= 1.9.2.
+RuboCop rules are meticulously configured by the rubocop-lts family of gems to ensure that a project is compatible with a specific version of Ruby. See: https://rubocop-lts.gitlab.io for more.

+ +

Checking RuboCop Violations

+ +

To check for RuboCop violations in this project, always use:

+ +
bundle exec rake rubocop_gradual:check
+
+ +

Do not use the standard RuboCop commands like:

+
    +
  • bundle exec rubocop
  • +
  • rubocop
  • +
+ +

Understanding the Lock File

+ +

The .rubocop_gradual.lock file tracks all current RuboCop violations in the project. This allows the team to:

+ +
    +
  1. Prevent new violations while gradually fixing existing ones
  2. +
  3. Track progress on code style improvements
  4. +
  5. Ensure CI builds don’t fail due to pre-existing violations
  6. +
+ +

Common Commands

+ +
    +
  • +Check violations +
      +
    • bundle exec rake rubocop_gradual
    • +
    • bundle exec rake rubocop_gradual:check
    • +
    +
  • +
  • +(Safe) Autocorrect violations, and update lockfile if no new violations +
      +
    • bundle exec rake rubocop_gradual:autocorrect
    • +
    +
  • +
  • +Force update the lock file (w/o autocorrect) to match violations present in code +
      +
    • bundle exec rake rubocop_gradual:force_update
    • +
    +
  • +
+ +

Workflow

+ +
    +
  1. Before submitting a PR, run bundle exec rake rubocop_gradual:autocorrect
    +a. or just the default bundle exec rake, as autocorrection is a pre-requisite of the default task.
  2. +
  3. If there are new violations, either: +
      +
    • Fix them in your code
    • +
    • Run bundle exec rake rubocop_gradual:force_update to update the lock file (only for violations you can’t fix immediately)
    • +
    +
  4. +
  5. Commit the updated .rubocop_gradual.lock file along with your changes
  6. +
+ +

Never add inline RuboCop disables

+ +

Do not add inline rubocop:disable / rubocop:enable comments anywhere in the codebase (including specs, except when following the few existing rubocop:disable patterns for a rule already being disabled elsewhere in the code). We handle exceptions in two supported ways:

+ +
    +
  • Permanent/structural exceptions: prefer adjusting the RuboCop configuration (e.g., in .rubocop.yml) to exclude a rule for a path or file pattern when it makes sense project-wide.
  • +
  • Temporary exceptions while improving code: record the current violations in .rubocop_gradual.lock via the gradual workflow: +
      +
    • +bundle exec rake rubocop_gradual:autocorrect (preferred; will autocorrect what it can and update the lock only if no new violations were introduced)
    • +
    • If needed, bundle exec rake rubocop_gradual:force_update (as a last resort when you cannot fix the newly reported violations immediately)
    • +
    +
  • +
+ +

In general, treat the rules as guidance to follow; fix violations rather than ignore them. For example, RSpec conventions in this project expect described_class to be used in specs that target a specific class under test.

+ +

Benefits of rubocop_gradual

+ +
    +
  • Allows incremental adoption of code style rules
  • +
  • Prevents CI failures due to pre-existing violations
  • +
  • Provides a clear record of code style debt
  • +
  • Enables focused efforts on improving code quality over time
  • +
+
+ + + +
+ + diff --git a/docs/file.SECURITY.html b/docs/file.SECURITY.html index e69de29bb..cdd6ccf6f 100644 --- a/docs/file.SECURITY.html +++ b/docs/file.SECURITY.html @@ -0,0 +1,105 @@ + + + + + + + File: SECURITY + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Security Policy

+ +

Supported Versions

+ + + + + + + + + + + + + + +
VersionSupported
1.latest
+ +

Security contact information

+ +

To report a security vulnerability, please use the
+Tidelift security contact.
+Tidelift will coordinate the fix and disclosure.

+ +

More detailed explanation of the process is in IRP.md.

+ +

Additional Support

+ +

If you are interested in support for versions older than the latest release,
+please consider sponsoring the project / maintainer @ https://liberapay.com/pboling/donate,
+or find other sponsorship links in the README.

+ +
+ + + +
+ + diff --git a/docs/index.html b/docs/index.html index e69de29bb..2d564f28b 100644 --- a/docs/index.html +++ b/docs/index.html @@ -0,0 +1,1699 @@ + + + + + + + File: README + + — Documentation by YARD 0.9.43 + + + + + + + + + + + + + + + + + + + + + +
+ + +

Galtzo FLOSS Logo by Aboling0, CC BY-SA 4.0 ruby-lang Logo, Yukihiro Matsumoto, Ruby Visual Identity Team, CC BY-SA 2.5 oauth2 Logo by Chris Messina, CC BY-SA 3.0

+ +

🔐 OAuth 2.0 Authorization Framework

+ +

Version GitHub tag (latest SemVer) License: MIT Downloads Rank CodeCov Test Coverage Coveralls Test Coverage QLTY Test Coverage QLTY Maintainability CI Heads CI Runtime Dependencies @ HEAD CI Current CI JRuby Deps Locked Deps Unlocked CI Supported CI Legacy CI Unsupported CI Ancient CI Test Coverage CI Style CodeQL Apache SkyWalking Eyes License Compatibility Check

+ +

if ci_badges.map(&:color).detect { it != "green"} ☝️ let me know, as I may have missed the discord notification.

+ +
+ +

if ci_badges.map(&:color).all? { it == "green"} 👇️ send money so I can do more of this. FLOSS maintenance is now my full-time job.

+ +

OpenCollective Backers OpenCollective Sponsors Sponsor Me on Github Liberapay Goal Progress Donate on PayPal Buy me a coffee Donate on Polar Donate at ko-fi.com

+ +
+ 👣 How will this project approach the September 2025 hostile takeover of RubyGems? 🚑️ + +I've summarized my thoughts in [this blog post](https://dev.to/galtzo/hostile-takeover-of-rubygems-my-thoughts-5hlo). + +
+ +

🌻 Synopsis

+ +

OAuth 2.0 is the industry-standard protocol for authorization.
+This is a RubyGem for implementing OAuth 2.0 clients (not servers) in Ruby applications.

+ +

⭐️ including OAuth 2.1 draft spec & OpenID Connect (OIDC)

+ +

Quick Examples

+ +
+ Convert the following `curl` command into a token request using this gem... + +
curl --request POST \
+  --url 'https://login.microsoftonline.com/REDMOND_REDACTED/oauth2/token' \
+  --header 'content-type: application/x-www-form-urlencoded' \
+  --data grant_type=client_credentials \
+  --data client_id=REDMOND_CLIENT_ID \
+  --data client_secret=REDMOND_CLIENT_SECRET \
+  --data resource=REDMOND_RESOURCE_UUID
+
+ +

NOTE: In the ruby version below, certain params are passed to the get_token call, instead of the client creation.

+ +
client = OAuth2::Client.new(
+  "REDMOND_CLIENT_ID", # client_id
+  "REDMOND_CLIENT_SECRET", # client_secret
+  auth_scheme: :request_body, # Other modes are supported: :basic_auth, :tls_client_auth, :private_key_jwt
+  token_url: "oauth2/token", # relative path, except with leading `/`, then absolute path
+  site: "https://login.microsoftonline.com/REDMOND_REDACTED",
+)
+client.
+  client_credentials. # There are many other types to choose from!
+  get_token(resource: "REDMOND_RESOURCE_UUID")
+
+ +

NOTE: header - The content type specified in the curl is already the default!

+ +
+ +
+ Complete E2E single file script against mock-oauth2-server + +
    +
  • E2E example uses navikt/mock-oauth2-server, which was added in v2.0.11
  • +
  • E2E example does not ship with the released gem, so clone the source to play with it.
  • +
+ +
docker compose -f docker-compose-ssl.yml up -d --wait
+ruby examples/e2e.rb
+# If your machine is slow or Docker pulls are cold, increase the wait:
+E2E_WAIT_TIMEOUT=120 ruby examples/e2e.rb
+# The mock server serves HTTP on 8080; the example points to http://localhost:8080 by default.
+
+ +

The output should be something like this:

+ +
➜  ruby examples/e2e.rb
+Access token (truncated): eyJraWQiOiJkZWZhdWx0...
+userinfo status: 200
+userinfo body: {"sub" => "demo-sub", "aud" => ["demo-aud"], "nbf" => 1757816758000, "iss" => "http://localhost:8080/default", "exp" => 1757820358000, "iat" => 1757816758000, "jti" => "d63b97a7-ebe5-4dea-93e6-d542caba6104"}
+E2E complete
+
+ +

Make sure to shut down the mock server when you are done:

+ +
docker compose -f docker-compose-ssl.yml down
+
+ +

Troubleshooting: validate connectivity to the mock server

+ +
    +
  • Check container status and port mapping: +
      +
    • docker compose -f docker-compose-ssl.yml ps
    • +
    +
  • +
  • From the host, try the discovery URL directly (this is what the example uses by default): +
      +
    • curl -v http://localhost:8080/default/.well-known/openid-configuration
    • +
    • If that fails immediately, also try: curl -v --connect-timeout 2 http://127.0.0.1:8080/default/.well-known/openid-configuration +
    • +
    +
  • +
  • From inside the container (to distinguish container vs. host networking): +
      +
    • docker exec -it oauth2-mock-oauth2-server-1 curl -v http://127.0.0.1:8080/default/.well-known/openid-configuration
    • +
    +
  • +
  • Simple TCP probe from the host: +
      +
    • nc -vz localhost 8080 # or: ruby -rsocket -e 'TCPSocket.new("localhost",8080).close; puts "tcp ok"'
    • +
    +
  • +
  • Inspect which host port 8080 is bound to (should be 8080): +
      +
    • docker inspect -f '{{ (index (index .NetworkSettings.Ports "8080/tcp") 0).HostPort }}' oauth2-mock-oauth2-server-1
    • +
    +
  • +
  • Look at server logs for readiness/errors: +
      +
    • docker logs -n 200 oauth2-mock-oauth2-server-1
    • +
    +
  • +
  • On Linux, ensure nothing else is bound to 8080 and that firewall/SELinux aren’t blocking: +
      +
    • ss -ltnp | grep :8080
    • +
    +
  • +
+ +

Notes

+ +
    +
  • Discovery URL pattern is: http://localhost:8080/<realm>/.well-known/openid-configuration, where <realm> defaults to default.
  • +
  • You can change these with env vars when running the example: +
      +
    • +E2E_ISSUER_BASE (default: http://localhost:8080)
    • +
    • +E2E_REALM (default: default)
    • +
    +
  • +
+ +
+ +

If it seems like you are in the wrong place, you might try one of these:

+ + + +

💡 Info you can shake a stick at

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Tokens to Remember +Gem name Gem namespace +
Works with JRuby +JRuby 9.1 Compat JRuby 9.2 Compat JRuby 9.3 Compat
JRuby 9.4 Compat JRuby 10.0 Compat JRuby HEAD Compat +
Works with Truffle Ruby +Truffle Ruby 22.3 Compat Truffle Ruby 23.0 Compat Truffle Ruby 23.1 Compat
Truffle Ruby 24.1 Compat +
Works with MRI Ruby 3 +Ruby 3.0 Compat Ruby 3.1 Compat Ruby 3.2 Compat Ruby 3.3 Compat Ruby 3.4 Compat Ruby HEAD Compat +
Works with MRI Ruby 2 +Ruby 2.2 Compat
Ruby 2.3 Compat Ruby 2.4 Compat Ruby 2.5 Compat Ruby 2.6 Compat Ruby 2.7 Compat +
Support & Community +Join Me on Daily.dev's RubyFriends Live Chat on Discord Get help from me on Upwork Get help from me on Codementor +
Source +Source on GitLab.com Source on CodeBerg.org Source on Github.com The best SHA: dQw4w9WgXcQ! +
Documentation +Current release on RubyDoc.info YARD on Galtzo.com Maintainer Blog GitLab Wiki GitHub Wiki +
Compliance +License: MIT Compatible with Apache Software Projects: Verified by SkyWalking Eyes 📄ilo-declaration-img Security Policy Contributor Covenant 2.1 SemVer 2.0.0 +
Style +Enforced Code Style Linter Keep-A-Changelog 1.0.0 Gitmoji Commits Compatibility appraised by: appraisal2 +
Maintainer 🎖️ +Follow Me on LinkedIn Follow Me on Ruby.Social Follow Me on Bluesky Contact Maintainer My technical writing +
+... 💖 +Find Me on WellFound: Find Me on CrunchBase My LinkTree More About Me 🧊 🐙 🛖 🧪 +
+ +

Compatibility

+ +

Compatible with MRI Ruby 2.2.0+, and concordant releases of JRuby, and TruffleRuby.

+ + + + + + + + + + + + + + +
🚚 Amazing test matrix was brought to you by🔎 appraisal2 🔎 and the color 💚 green 💚
👟 Check it out!github.com/appraisal-rb/appraisal2
+ +

Federated DVCS

+ +
+ Find this repo on federated forges (Coming soon!) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Federated DVCS RepositoryStatusIssuesPRsWikiCIDiscussions
🧪 ruby-oauth/oauth2 on GitLab +The Truth💚💚💚🐭 Tiny Matrix
🧊 ruby-oauth/oauth2 on CodeBerg +An Ethical Mirror (Donate)💚💚⭕️ No Matrix
🐙 ruby-oauth/oauth2 on GitHub +Another Mirror💚💚💚💯 Full Matrix💚
🎮️ Discord Server +Live Chat on DiscordLet’stalkaboutthislibrary!
+ +
+ +

Enterprise Support Tidelift +

+ +

Available as part of the Tidelift Subscription.

+ +
+ Need enterprise-level guarantees? + +

The maintainers of this and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use.

+ +

Get help from me on Tidelift

+ +
    +
  • 💡Subscribe for support guarantees covering all your FLOSS dependencies
  • +
  • 💡Tidelift is part of Sonar +
  • +
  • 💡Tidelift pays maintainers to maintain the software you depend on!
    📊@Pointy Haired Boss: An enterprise support subscription is “never gonna let you down”, and supports open source maintainers
  • +
+ +

Alternatively:

+ +
    +
  • Live Chat on Discord
  • +
  • Get help from me on Upwork
  • +
  • Get help from me on Codementor
  • +
+ +
+ +

✨ Installation

+ +

Install the gem and add to the application’s Gemfile by executing:

+ +
bundle add oauth2
+
+ +

If bundler is not being used to manage dependencies, install the gem by executing:

+ +
gem install oauth2
+
+ +

🔒 Secure Installation

+ +
+ For Medium or High Security Installations + +

This gem is cryptographically signed, and has verifiable SHA-256 and SHA-512 checksums by +stone_checksums. Be sure the gem you install hasn’t been tampered with +by following the instructions below.

+ +

Add my public key (if you haven’t already, expires 2045-04-29) as a trusted certificate:

+ +
gem cert --add <(curl -Ls https://raw.github.com/galtzo-floss/certs/main/pboling.pem)
+
+ +

You only need to do that once. Then proceed to install with:

+ +
gem install oauth2 -P MediumSecurity
+
+ +

The MediumSecurity trust profile will verify signed gems, but allow the installation of unsigned dependencies.

+ +

This is necessary because not all of oauth2’s dependencies are signed, so we cannot use HighSecurity.

+ +

If you want to up your security game full-time:

+ +
bundle config set --global trust-policy MediumSecurity
+
+ +

MediumSecurity instead of HighSecurity is necessary if not all the gems you use are signed.

+ +

NOTE: Be prepared to track down certs for signed gems and add them the same way you added mine.

+ +
+ +

What is new for v2.0?

+ +
    +
  • Works with Ruby versions >= 2.2
  • +
  • Drop support for the expired MAC Draft (all versions)
  • +
  • Support IETF rfc7515 JSON Web Signature - JWS (since v2.0.12) +
      +
    • Support JWT kid for key discovery and management
    • +
    +
  • +
  • Support IETF rfc7523 JWT Bearer Tokens (since v2.0.0)
  • +
  • Support IETF rfc7231 Relative Location in Redirect (since v2.0.0)
  • +
  • Support IETF rfc6749 Don’t set oauth params when nil (since v2.0.0)
  • +
  • Support IETF rfc7009 Token Revocation (since v2.0.10, updated in v2.0.13 to support revocation via URL-encoded parameters)
  • +
  • Support OIDC 1.0 Private Key JWT; based on the OAuth JWT assertion specification (RFC 7523) +
  • +
  • Support new formats, including from jsonapi.org: application/vdn.api+json, application/vnd.collection+json, application/hal+json, application/problem+json +
  • +
  • Adds option to OAuth2::Client#get_token: +
      +
    • +:access_token_class (AccessToken); user specified class to use for all calls to get_token +
    • +
    +
  • +
  • Adds option to OAuth2::AccessToken#initialize: +
      +
    • +:expires_latency (nil); number of seconds by which AccessToken validity will be reduced to offset latency
    • +
    +
  • +
  • By default, keys are transformed to snake case. +
      +
    • Original keys will still work as previously, in most scenarios, thanks to snaky_hash gem.
    • +
    • However, this is a breaking change if you rely on response.parsed.to_h to retain the original case, and the original wasn’t snake case, as the keys in the result will be snake case.
    • +
    • As of version 2.0.4 you can turn key transformation off with the snaky: false option.
    • +
    +
  • +
  • By default, the :auth_scheme is now :basic_auth (instead of :request_body) +
      +
    • Third-party strategies and gems may need to be updated if a provider was requiring client id/secret in the request body
    • +
    +
  • +
  • … A lot more
  • +
+ +

Compatibility

+ +

Targeted ruby compatibility is non-EOL versions of Ruby, currently 3.2, 3.3, and 3.4.
+Compatibility is further distinguished as “Best Effort Support” or “Incidental Support” for older versions of Ruby.
+This gem will install on Ruby versions >= v2.2 for 2.x releases.
+See 1-4-stable branch for older rubies.

+ +
+ Ruby Engine Compatibility Policy + +

This gem is tested against MRI, JRuby, and Truffleruby. +Each of those has varying versions that target a specific version of MRI Ruby. +This gem should work in the just-listed Ruby engines according to the targeted MRI compatibility in the table below. +If you would like to add support for additional engines, +see gemfiles/README.md, then submit a PR to the correct maintenance branch as according to the table below.

+ +
+ +
+ Ruby Version Compatibility Policy + +

If something doesn’t work on one of these interpreters, it’s a bug.

+ +

This library may inadvertently work (or seem to work) on other Ruby +implementations; however, support will only be provided for the versions listed +above.

+ +

If you would like this library to support another Ruby version, you may +volunteer to be a maintainer. Being a maintainer entails making sure all tests +run and pass on that implementation. When something breaks on your +implementation, you will be responsible for providing patches in a timely +fashion. If critical issues for a particular implementation exist at the time +of a major release, support for that Ruby version may be dropped.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 Ruby OAuth2 VersionMaintenance BranchTargeted SupportBest Effort SupportIncidental Support
1️⃣2.0.xmain3.2, 3.3, 3.42.5, 2.6, 2.7, 3.0, 3.12.2, 2.3, 2.4
2️⃣1.4.x1-4-stable3.2, 3.3, 3.42.5, 2.6, 2.7, 3.0, 3.11.9, 2.0, 2.1, 2.2, 2.3, 2.4
3️⃣olderN/ABest of luck to you!Please upgrade! 
+ +

NOTE: The 1.4 series will only receive critical security updates.
+See SECURITY.md and IRP.md.

+ +

⚙️ Configuration

+ +

Global settings for the library:

+ +
OAuth2.configure do |config|
+  config.silence_extra_tokens_warning = false # default: true
+  config.silence_no_tokens_warning = false    # default: true
+end
+
+ +

Filtering-related settings:

+ +
OAuth2.configure do |config|
+  config.filtered_label = "[REDACTED]" # default: "[FILTERED]"
+  config.filtered_debug_keys += ["client_assertion"]
+end
+
+ +
    +
  • +filtered_label controls the placeholder used when sensitive values are filtered from inspected objects and debug logging output.
  • +
  • +filtered_debug_keys controls which key names have their values redacted from debug logging output when OAUTH_DEBUG=true.
  • +
  • Debug logging remains opt-in and should still be used cautiously in production environments.
  • +
+ +

🔧 Basic Usage

+ +

Client Initialization Options

+ +

OAuth2::Client.new accepts several options:

+ +
    +
  • +:site: The base URL for the OAuth 2.0 provider.
  • +
  • +:authorize_url: The authorization endpoint (default: "oauth/authorize").
  • +
  • +:token_url: The token endpoint (default: "oauth/token").
  • +
  • +:auth_scheme: The authentication scheme (:basic_auth, :request_body, :tls_client_auth, :private_key_jwt). Default is :basic_auth.
  • +
  • +:connection_opts: Options for the underlying Faraday connection (timeouts, proxy, etc.).
  • +
  • +:raise_errors: Whether to raise OAuth2::Error on 400+ responses (default: true).
  • +
+ +
+ authorize_url and token_url + +

+authorize_url and token_url are on site root (Just Works!)

+ +
require "oauth2"
+client = OAuth2::Client.new("client_id", "client_secret", site: "https://example.org")
+# => #<OAuth2::Client:0x00000001204c8288 @id="client_id", @secret="client_sec...
+client.auth_code.authorize_url(redirect_uri: "http://localhost:8080/oauth2/callback")
+# => "https://example.org/oauth/authorize?client_id=client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&response_type=code"
+
+access = client.auth_code.get_token("authorization_code_value", redirect_uri: "http://localhost:8080/oauth2/callback", headers: {"Authorization" => "Basic some_password"})
+response = access.get("/api/resource", params: {"query_foo" => "bar"})
+response.class.name
+# => OAuth2::Response
+
+ +

Relative authorize_url and token_url (Not on site root, Just Works!)

+ +

In the above example, the default Authorization URL is oauth/authorize and default Access Token URL is oauth/token, and, as they are missing a leading /, both are relative.

+ +
client = OAuth2::Client.new("client_id", "client_secret", site: "https://example.org/nested/directory/on/your/server")
+# => #<OAuth2::Client:0x00000001204c8288 @id="client_id", @secret="client_sec...
+client.auth_code.authorize_url(redirect_uri: "http://localhost:8080/oauth2/callback")
+# => "https://example.org/nested/directory/on/your/server/oauth/authorize?client_id=client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&response_type=code"
+
+ +

Customize authorize_url and token_url +

+ +

You can specify custom URLs for authorization and access token, and when using a leading / they will not be relative, as shown below:

+ +
client = OAuth2::Client.new(
+  "client_id",
+  "client_secret",
+  site: "https://example.org/nested/directory/on/your/server",
+  authorize_url: "/jaunty/authorize/",
+  token_url: "/stirrups/access_token",
+)
+# => #<OAuth2::Client:0x00000001204c8288 @id="client_id", @secret="client_sec...
+client.auth_code.authorize_url(redirect_uri: "http://localhost:8080/oauth2/callback")
+# => "https://example.org/jaunty/authorize/?client_id=client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&response_type=code"
+client.class.name
+# => OAuth2::Client
+
+ +
+ +

Advanced Initializers

+ +
client = OAuth2::Client.new(id, secret, site: site) do |faraday|
+  faraday.request(:url_encoded)
+  faraday.adapter(:net_http_persistent)
+end
+
+ +

AccessToken Features

+ +

Instances of OAuth2::AccessToken handle request signing and token expiration.

+ +
    +
  • +Snake Case & Indifferent Access: response.parsed returns a SnakyHash allowing access via string/symbol and snake_case keys even if the provider returns CamelCase.
  • +
  • +Auto-Refresh: You can manually check token.expired? and call token.refresh.
  • +
  • +Serialization: Persist tokens using token.to_hash and restore via OAuth2::AccessToken.from_hash(client, hash).
  • +
+ +

snake_case and indifferent access in Response#parsed

+ +
response = access.get("/api/resource", params: {"query_foo" => "bar"})
+# Even if the actual response is CamelCase. it will be made available as snaky:
+JSON.parse(response.body)         # => {"accessToken"=>"aaaaaaaa", "additionalData"=>"additional"}
+response.parsed                   # => {"access_token"=>"aaaaaaaa", "additional_data"=>"additional"}
+response.parsed.access_token      # => "aaaaaaaa"
+response.parsed[:access_token]    # => "aaaaaaaa"
+response.parsed.additional_data   # => "additional"
+response.parsed[:additional_data] # => "additional"
+response.parsed.class.name        # => SnakyHash::StringKeyed (from snaky_hash gem)
+
+ +

Serialization

+ +

As of v2.0.11, if you need to serialize the parsed result, you can!

+ +

There are two ways to do this, globally, or discretely. The discrete way is recommended.

+ +
Global Serialization Config
+ +

Globally configure SnakyHash::StringKeyed to use the serializer. Put this in your code somewhere reasonable (like an initializer for Rails).

+ +
SnakyHash::StringKeyed.class_eval do
+  extend SnakyHash::Serializer
+end
+
+ +
Discrete Serialization Config
+ +

Discretely configure a custom Snaky Hash class to use the serializer.

+ +
class MySnakyHash < SnakyHash::StringKeyed
+  # Give this hash class `dump` and `load` abilities!
+  extend SnakyHash::Serializer
+end
+
+# And tell your client to use the custom class in each call:
+client = OAuth2::Client.new("client_id", "client_secret", site: "https://example.org/oauth2")
+token = client.get_token({snaky_hash_klass: MySnakyHash})
+
+ +
Serialization Extensions
+ +

These extensions work regardless of whether you used the global or discrete config above.

+ +

There are a few hacks you may need in your class to support Ruby < 2.4.2 or < 2.6.
+They are likely not needed if you are on a newer Ruby.
+Expand the examples below, or the ruby-oauth/snaky_hash gem,
+or response_spec.rb, for more ideas, especially if you need to study the hacks for older Rubies.

+ +
+ See Examples + +
class MySnakyHash < SnakyHash::StringKeyed
+  # Give this hash class `dump` and `load` abilities!
+  extend SnakyHash::Serializer
+
+  #### Serialization Extentions
+  #
+  # Act on the non-hash values (including the values of hashes) as they are dumped to JSON
+  # In other words, this retains nested hashes, and only the deepest leaf nodes become bananas.
+  # WARNING: This is a silly example!
+  dump_value_extensions.add(:to_fruit) do |value|
+    "banana" # => Make values "banana" on dump
+  end
+
+  # Act on the non-hash values (including the values of hashes) as they are loaded from the JSON dump
+  # In other words, this retains nested hashes, and only the deepest leaf nodes become ***.
+  # WARNING: This is a silly example!
+  load_value_extensions.add(:to_stars) do |value|
+    "***" # Turn dumped bananas into *** when they are loaded
+  end
+
+  # Act on the entire hash as it is prepared for dumping to JSON
+  # WARNING: This is a silly example!
+  dump_hash_extensions.add(:to_cheese) do |value|
+    if value.is_a?(Hash)
+      value.transform_keys do |key|
+        split = key.split("_")
+        first_word = split[0]
+        key.sub(first_word, "cheese")
+      end
+    else
+      value
+    end
+  end
+
+  # Act on the entire hash as it is loaded from the JSON dump
+  # WARNING: This is a silly example!
+  load_hash_extensions.add(:to_pizza) do |value|
+    if value.is_a?(Hash)
+      res = klass.new
+      value.keys.each_with_object(res) do |key, result|
+        split = key.split("_")
+        last_word = split[-1]
+        new_key = key.sub(last_word, "pizza")
+        result[new_key] = value[key]
+      end
+      res
+    else
+      value
+    end
+  end
+end
+
+ +
+ +

Prefer camelCase over snake_case? => snaky: false

+ +
response = access.get("/api/resource", params: {"query_foo" => "bar"}, snaky: false)
+JSON.parse(response.body)         # => {"accessToken"=>"aaaaaaaa", "additionalData"=>"additional"}
+response.parsed                   # => {"accessToken"=>"aaaaaaaa", "additionalData"=>"additional"}
+response.parsed["accessToken"]    # => "aaaaaaaa"
+response.parsed["additionalData"] # => "additional"
+response.parsed.class.name        # => Hash (just, regular old Hash)
+
+ +
+ Debugging & Logging + +

Set an environment variable as per usual (e.g. with dotenv).

+ +
# will log both request and response, including bodies
+ENV["OAUTH_DEBUG"] = "true"
+
+ +

By default, debug output will go to $stdout. This can be overridden when +initializing your OAuth2::Client.

+ +

Sensitive values are filtered from debug logging output using:

+ +
    +
  • OAuth2.config[:filtered_label]
  • +
  • OAuth2.config[:filtered_debug_keys]
  • +
+ +

Debug logging remains opt-in and should still be used cautiously in production environments.

+ +
require "oauth2"
+client = OAuth2::Client.new(
+  "client_id",
+  "client_secret",
+  site: "https://example.org",
+  logger: Logger.new("example.log", "weekly"),
+)
+
+ +
+ +

Request Target Trust Boundaries

+ +

This gem supports request flows that can involve absolute URLs in addition to relative paths.
+That flexibility can expand trust boundaries when a token-bearing client is asked to send requests
+to caller-provided targets.

+ +

Practical guidance:

+ +
    +
  • prefer relative paths where practical
  • +
  • do not pass untrusted absolute URLs into token-bearing clients
  • +
  • validate or allowlist request targets at the application layer today if your deployment has strict trust-boundary requirements
  • +
+ +

This release line does not yet enforce same-host or allowlist request policy automatically.
+If stricter outbound request controls are needed, they should currently be implemented by the calling application.

+ +

OAuth2::Response

+ +

The AccessToken methods #get, #post, #put and #delete and the generic #request
+will return an instance of the OAuth2::Response class.

+ +

This instance contains a #parsed method that will parse the response body and
+return a Hash-like SnakyHash::StringKeyed if the Content-Type is application/x-www-form-urlencoded or if
+the body is a JSON object. It will return an Array if the body is a JSON
+array. Otherwise, it will return the original body string.

+ +

The original response body, headers, and status can be accessed via their
+respective methods.

+ +

OAuth2::AccessToken

+ +

If you have an existing Access Token for a user, you can initialize an instance
+using various class methods including the standard new, from_hash (if you have
+a hash of the values), or from_kvform (if you have an
+application/x-www-form-urlencoded encoded string of the values).

+ +

Options (since v2.0.x unless noted):

+ +
    +
  • + + + + + + + +
    +expires_latency (Integernil): Seconds to subtract from expires_in when computing #expired? to offset latency.
    +
  • +
  • + + + + + + + + +
    +token_name (StringSymbolnil): When multiple token-like fields exist in responses, select the field name to use as the access token (since v2.0.10).
    +
  • +
  • + + + + + + + + +
    +mode (SymbolProcHash): Controls how the token is transmitted on requests made via this AccessToken instance.
    +
      +
    • +:header — Send as Authorization: Bearer header (default and preferred by OAuth 2.1 draft guidance). +
    • +
    • +:query — Send as access_token query parameter (discouraged in general, but required by some providers).
    • +
    • Verb-dependent (since v2.0.15): Provide either: +
        +
      • a Proc taking |verb| and returning :header or :query, or
      • +
      • a Hash with verb symbols as keys, for example {get: :query, post: :header, delete: :header}.
      • +
      +
    • +
    +
  • +
+ +

Note: Verb-dependent mode supports providers like Instagram that require query mode for GET and header mode for POST/DELETE

+ +
    +
  • Verb-dependent mode via Proc was added in v2.0.15
  • +
  • Verb-dependent mode via Hash was added in v2.0.16
  • +
+ +

OAuth2::Error

+ +

On 400+ status code responses, an OAuth2::Error will be raised. If it is a
+standard OAuth2 error response, the body will be parsed and #code and #description will contain the values provided from the error and
+error_description parameters. The #response property of OAuth2::Error will
+always contain the OAuth2::Response instance.

+ +

If you do not want an error to be raised, you may use :raise_errors => false
+option on initialization of the client. In this case the OAuth2::Response
+instance will be returned as usual and on 400+ status code responses, the
+Response instance will contain the OAuth2::Error instance.

+ +

Authorization Grants

+ +

Currently, the Authorization Code, Implicit, Resource Owner Password Credentials, Client Credentials, and Assertion
+authentication grant types have helper strategy classes that simplify client
+use. They are available via the #auth_code,
+#implicit,
+#password,
+#client_credentials, and
+#assertion methods respectively.

+ +

OAuth 2.1 (draft) Note:

+ +
    +
  • +PKCE is required for all OAuth clients using the authorization code flow (especially public clients). Implement PKCE in your app when required by your provider. See RFC 7636 and RFC 8252.
  • +
  • +Implicit grant (response_type=token) and Resource Owner Password Credentials grant are omitted from OAuth 2.1; they remain here for OAuth 2.0 compatibility but should be avoided for new apps.
  • +
  • +Redirect URIs must be compared using exact string matching by the Authorization Server.
  • +
+ +
+ OAuth 2.1 (draft) References + +
    +
  • OAuth 2.1 draft: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13
  • +
  • Aaron Parecki: https://aaronparecki.com/2019/12/12/21/its-time-for-oauth-2-dot-1
  • +
  • FusionAuth: https://fusionauth.io/blog/2020/04/15/whats-new-in-oauth-2-1
  • +
  • Okta: https://developer.okta.com/blog/2019/12/13/oauth-2-1-how-many-rfcs
  • +
  • Video: https://www.youtube.com/watch?v=g_aVPdwBTfw
  • +
  • Differences overview: https://fusionauth.io/learn/expert-advice/oauth/differences-between-oauth-2-oauth-2-1/
  • +
+ +
+ +

These aren’t full examples, but demonstrative of the differences between usage for each strategy.

+ +
auth_url = client.auth_code.authorize_url(redirect_uri: "http://localhost:8080/oauth/callback")
+access = client.auth_code.get_token("code_value", redirect_uri: "http://localhost:8080/oauth/callback")
+
+auth_url = client.implicit.authorize_url(redirect_uri: "http://localhost:8080/oauth/callback")
+# get the token params in the callback and
+access = OAuth2::AccessToken.from_kvform(client, query_string)
+
+access = client.password.get_token("username", "password")
+
+access = client.client_credentials.get_token
+
+# Client Assertion Strategy
+# see: https://tools.ietf.org/html/rfc7523
+claimset = {
+  iss: "http://localhost:3001",
+  aud: "http://localhost:8080/oauth2/token",
+  sub: "me@example.com",
+  exp: Time.now.utc.to_i + 3600,
+}
+assertion_params = [claimset, "HS256", "secret_key"]
+access = client.assertion.get_token(assertion_params)
+
+# The `access` (i.e. access token) is then used like so:
+access.token # actual access_token string, if you need it somewhere
+access.get("/api/stuff") # making api calls with access token
+
+ +

If you want to specify additional headers to be sent out with the
+request, add a ‘headers’ hash under ‘params’:

+ +
access = client.auth_code.get_token("code_value", redirect_uri: "http://localhost:8080/oauth/callback", headers: {"Some" => "Header"})
+
+ +

You can always use the #request method on the OAuth2::Client instance to make
+requests for tokens for any Authentication grant type.

+ +

📘 Comprehensive Usage

+ +

Common Flows (end-to-end)

+ +
    +
  • Authorization Code (server-side web app):
  • +
+ +
require "oauth2"
+client = OAuth2::Client.new(
+  ENV["CLIENT_ID"],
+  ENV["CLIENT_SECRET"],
+  site: "https://provider.example.com",
+  redirect_uri: "https://my.app.example.com/oauth/callback",
+)
+
+# Step 1: redirect user to consent
+state = SecureRandom.hex(16)
+auth_url = client.auth_code.authorize_url(scope: "openid profile email", state: state)
+# redirect_to auth_url
+
+# Step 2: handle the callback
+# params[:code], params[:state]
+raise "state mismatch" unless params[:state] == state
+access = client.auth_code.get_token(params[:code])
+
+# Step 3: call APIs
+profile = access.get("/api/v1/me").parsed
+
+ +
    +
  • Client Credentials (machine-to-machine):
  • +
+ +
client = OAuth2::Client.new(ENV["CLIENT_ID"], ENV["CLIENT_SECRET"], site: "https://provider.example.com")
+access = client.client_credentials.get_token(audience: "https://api.example.com")
+resp = access.get("/v1/things")
+
+ +
    +
  • Resource Owner Password (legacy; avoid when possible):
  • +
+ +
access = client.password.get_token("jdoe", "s3cret", scope: "read")
+
+ +

Examples

+ +
+ JHipster UAA (Spring Cloud) password grant example (legacy; avoid when possible) + +
# This converts a Postman/Net::HTTP multipart token request to oauth2 gem usage.
+# JHipster UAA typically exposes the token endpoint at /uaa/oauth/token.
+# The original snippet included:
+# - Basic Authorization header for the client (web_app:changeit)
+# - X-XSRF-TOKEN header from a cookie (some deployments require it)
+# - grant_type=password with username/password and client_id
+# Using oauth2 gem, you don't need to build multipart bodies; the gem sends
+# application/x-www-form-urlencoded as required by RFC 6749.
+
+require "oauth2"
+
+client = OAuth2::Client.new(
+  "web_app",            # client_id
+  "changeit",           # client_secret
+  site: "http://localhost:8080/uaa",
+  token_url: "/oauth/token",      # absolute under site (or "oauth/token" relative)
+  auth_scheme: :basic_auth,         # sends HTTP Basic Authorization header
+)
+
+# If your UAA requires an XSRF header for the token call, provide it as a header.
+# Often this is not required for token endpoints, but if your gateway enforces it,
+# obtain the value from the XSRF-TOKEN cookie and pass it here.
+xsrf_token = ENV["X_XSRF_TOKEN"] # e.g., pulled from a prior set-cookie value
+
+access = client.password.get_token(
+  "admin",                 # username
+  "admin",                 # password
+  headers: xsrf_token ? {"X-XSRF-TOKEN" => xsrf_token} : {},
+  # JHipster commonly also accepts/needs the client_id in the body; include if required:
+  # client_id: "web_app",
+)
+
+puts access.token
+puts access.to_hash # full token response
+
+ +

Notes:

+ +
    +
  • Resource Owner Password Credentials (ROPC) is deprecated in OAuth 2.1 and discouraged. Prefer Authorization Code + PKCE.
  • +
  • If your deployment strictly demands the X-XSRF-TOKEN header, first fetch it from an endpoint that sets the XSRF-TOKEN cookie (often “/” or a login page) and pass it to headers.
  • +
  • For Basic auth, auth_scheme: :basic_auth handles the Authorization header; you do not need to base64-encode manually.
  • +
+ +
+ +

Verb‑dependent Token Mode

+ +

Providers like Instagram require the access token to be sent differently depending on the HTTP verb:

+ +
    +
  • GET requests: token must be in the query string (?access_token=…)
  • +
  • POST/DELETE requests: token must be in the Authorization header (Bearer …)
  • +
+ +

Since v2.0.15, you can configure an AccessToken with a verb‑dependent mode. The gem will choose how to send the token based on the request method.

+ +

Tips:

+ +
    +
  • Avoid query‑string bearer tokens unless required by your provider. Instagram explicitly requires it for GET requests.
  • +
  • If you need a custom rule, you can pass a Proc for mode, e.g. mode: ->(verb) { verb == :get ? :query : :header }.
  • +
+ +
+ Instagram API Example + +

Example: exchanging and refreshing long‑lived Instagram tokens, and making API calls

+ +
require "oauth2"
+
+# NOTE: Users authenticate via Facebook Login to obtain a short‑lived user token (not shown here).
+# See Facebook Login docs for obtaining the initial short‑lived token.
+
+client = OAuth2::Client.new(nil, nil, site: "https://graph.instagram.com")
+
+# Start with a short‑lived token you already obtained via Facebook Login
+short_lived = OAuth2::AccessToken.new(
+  client,
+  ENV["IG_SHORT_LIVED_TOKEN"],
+  # Key part: verb‑dependent mode
+  mode: {get: :query, post: :header, delete: :header},
+)
+
+# 1) Exchange for a long‑lived token (Instagram requires GET with access_token in query)
+#    Endpoint: GET https://graph.instagram.com/access_token
+#    Params: grant_type=ig_exchange_token, client_secret=APP_SECRET
+exchange = short_lived.get(
+  "/access_token",
+  params: {
+    grant_type: "ig_exchange_token",
+    client_secret: ENV["IG_APP_SECRET"],
+    # access_token param will be added automatically by the AccessToken (mode => :query for GET)
+  },
+)
+long_lived_token_value = exchange.parsed["access_token"]
+
+long_lived = OAuth2::AccessToken.new(
+  client,
+  long_lived_token_value,
+  mode: {get: :query, post: :header, delete: :header},
+)
+
+# 2) Refresh the long‑lived token (Instagram uses GET with token in query)
+#    Endpoint: GET https://graph.instagram.com/refresh_access_token
+refresh_resp = long_lived.get(
+  "/refresh_access_token",
+  params: {grant_type: "ig_refresh_token"},
+)
+long_lived = OAuth2::AccessToken.new(
+  client,
+  refresh_resp.parsed["access_token"],
+  mode: {get: :query, post: :header, delete: :header},
+)
+
+# 3) Typical API GET request (token in query automatically)
+me = long_lived.get("/me", params: {fields: "id,username"}).parsed
+
+# 4) Example POST (token sent via Bearer header automatically)
+# Note: Replace the path/params with a real Instagram Graph API POST you need,
+# such as publishing media via the Graph API endpoints.
+# long_lived.post("/me/media", body: {image_url: "https://...", caption: "hello"})
+
+ +
+ +

Refresh Tokens

+ +

When the server issues a refresh_token, you can refresh manually or implement an auto-refresh wrapper.

+ +
    +
  • Manual refresh:
  • +
+ +
if access.expired?
+  access = access.refresh
+end
+
+ +
    +
  • Auto-refresh wrapper pattern:
  • +
+ +
class AutoRefreshingToken
+  def initialize(token_provider, store: nil)
+    @token = token_provider
+    @store = store # e.g., something that responds to read/write for token data
+  end
+
+  def with(&blk)
+    tok = ensure_fresh!
+    blk ? blk.call(tok) : tok
+  rescue OAuth2::Error => e
+    # If a 401 suggests token invalidation, try one refresh and retry once
+    if e.response && e.response.status == 401 && @token.refresh_token
+      @token = @token.refresh
+      @store.write(@token.to_hash) if @store
+      retry
+    end
+    raise
+  end
+
+private
+
+  def ensure_fresh!
+    if @token.expired? && @token.refresh_token
+      @token = @token.refresh
+      @store.write(@token.to_hash) if @store
+    end
+    @token
+  end
+end
+
+# usage
+keeper = AutoRefreshingToken.new(access)
+keeper.with { |tok| tok.get("/v1/protected") }
+
+ +

Persist the token across processes using AccessToken#to_hash and AccessToken.from_hash(client, hash).

+ +

Token Revocation (RFC 7009)

+ +

You can revoke either the access token or the refresh token.

+ +
# Revoke the current access token
+access.revoke(token_type_hint: :access_token)
+
+# Or explicitly revoke the refresh token (often also invalidates associated access tokens)
+access.revoke(token_type_hint: :refresh_token)
+
+ +

Client Configuration Tips

+ +

Mutual TLS (mTLS) client authentication

+ +

Some providers require OAuth requests (including the token request and subsequent API calls) to be sender‑constrained using mutual TLS (mTLS). With this gem, you enable mTLS by providing a client certificate/private key to Faraday via connection_opts.ssl and, if your provider requires it for client authentication, selecting the tls_client_auth auth_scheme.

+ +

Example using PEM files (certificate and key):

+ +
require "oauth2"
+require "openssl"
+
+client = OAuth2::Client.new(
+  ENV.fetch("CLIENT_ID"),
+  ENV.fetch("CLIENT_SECRET"),
+  site: "https://example.com",
+  authorize_url: "/oauth/authorize/",
+  token_url: "/oauth/token/",
+  auth_scheme: :tls_client_auth, # if your AS requires mTLS-based client authentication
+  connection_opts: {
+    ssl: {
+      client_cert: OpenSSL::X509::Certificate.new(File.read("localhost.pem")),
+      client_key: OpenSSL::PKey::RSA.new(File.read("localhost-key.pem")),
+      # Optional extras, uncomment as needed:
+      # ca_file: "/path/to/ca-bundle.pem",   # custom CA(s)
+      # verify: true                           # enable server cert verification (recommended)
+    },
+  },
+)
+
+# Example token request (any grant type can be used). The mTLS handshake
+# will occur automatically on HTTPS calls using the configured cert/key.
+access = client.client_credentials.get_token
+
+# Subsequent resource requests will also use mTLS on HTTPS endpoints of `site`:
+resp = access.get("/v1/protected")
+
+ +

Notes:

+ +
    +
  • Files must contain the appropriate PEMs. The private key may be encrypted; if so, pass a password to OpenSSL::PKey::RSA.new(File.read(path), ENV["KEY_PASSWORD"]).
  • +
  • If your certificate and key are in a PKCS#12/PFX bundle, you can load them like: +
      +
    • p12 = OpenSSL::PKCS12.new(File.read("client.p12"), ENV["P12_PASSWORD"])
    • +
    • client_cert = p12.certificate; client_key = p12.key
    • +
    +
  • +
  • Server trust: +
      +
    • If your environment does not have system CAs, specify ca_file or ca_path inside the ssl: hash.
    • +
    • Keep verify: true in production. Set verify: false only for local testing.
    • +
    +
  • +
  • Faraday adapter: Any adapter that supports Ruby’s OpenSSL should work. net_http (default) and net_http_persistent are common choices.
  • +
  • Scope of mTLS: The SSL client cert is applied to any HTTPS request made by this client (token and resource requests) to the configured site base URL (and absolute URLs you call with the same client).
  • +
  • OIDC tie-in: Some OPs require tls_client_auth at the token endpoint per OIDC/OAuth specifications. That is enabled via auth_scheme: :tls_client_auth as shown above.
  • +
+ +

Authentication schemes for the token request

+ +
OAuth2::Client.new(
+  id,
+  secret,
+  site: "https://provider.example.com",
+  auth_scheme: :basic_auth, # default. Alternatives: :request_body, :tls_client_auth, :private_key_jwt
+)
+
+ +

Faraday connection, timeouts, proxy, custom adapter/middleware:

+ +
client = OAuth2::Client.new(
+  id,
+  secret,
+  site: "https://provider.example.com",
+  connection_opts: {
+    request: {open_timeout: 5, timeout: 15},
+    proxy: ENV["HTTPS_PROXY"],
+    ssl: {verify: true},
+  },
+) do |faraday|
+  faraday.request(:url_encoded)
+  # faraday.response :logger, Logger.new($stdout) # see OAUTH_DEBUG below
+  faraday.adapter(:net_http_persistent) # or any Faraday adapter you need
+end
+
+ +
Using flat query params (Faraday::FlatParamsEncoder)
+ +

Some APIs expect repeated key parameters to be sent as flat params rather than arrays. Faraday provides FlatParamsEncoder for this purpose. You can configure the oauth2 client to use it when building requests.

+ +
require "faraday"
+
+client = OAuth2::Client.new(
+  id,
+  secret,
+  site: "https://api.example.com",
+  # Pass Faraday connection options to make FlatParamsEncoder the default
+  connection_opts: {
+    request: {params_encoder: Faraday::FlatParamsEncoder},
+  },
+) do |faraday|
+  faraday.request(:url_encoded)
+  faraday.adapter(:net_http)
+end
+
+access = client.client_credentials.get_token
+
+# Example of a GET with two flat filter params (not an array):
+# Results in: ?filter=order.clientCreatedTime%3E1445006997000&filter=order.clientCreatedTime%3C1445611797000
+resp = access.get(
+  "/v1/orders",
+  params: {
+    # Provide the values as an array; FlatParamsEncoder expands them as repeated keys
+    filter: [
+      "order.clientCreatedTime>1445006997000",
+      "order.clientCreatedTime<1445611797000",
+    ],
+  },
+)
+
+ +

If you instead need to build a raw Faraday connection yourself, the equivalent configuration is:

+ +
conn = Faraday.new("https://api.example.com", request: {params_encoder: Faraday::FlatParamsEncoder})
+
+ +

Redirection

+ +

The library follows up to max_redirects (default 5).
+You can override per-client via options[:max_redirects].

+ +

Handling Responses and Errors

+ +
    +
  • Parsing:
  • +
+ +
resp = access.get("/v1/thing")
+resp.status     # Integer
+resp.headers    # Hash
+resp.body       # String
+resp.parsed     # SnakyHash::StringKeyed or Array when JSON array
+
+ +
    +
  • Error handling:
  • +
+ +
begin
+  access.get("/v1/forbidden")
+rescue OAuth2::Error => e
+  e.code         # OAuth2 error code (when present)
+  e.description  # OAuth2 error description (when present)
+  e.response     # OAuth2::Response (full access to status/headers/body)
+end
+
+ +
    +
  • Disable raising on 4xx/5xx to inspect the response yourself:
  • +
+ +
client = OAuth2::Client.new(id, secret, site: site, raise_errors: false)
+res = client.request(:get, "/v1/maybe-errors")
+if res.status == 429
+  sleep res.headers["retry-after"].to_i
+end
+
+ +

Making Raw Token Requests

+ +

If a provider requires non-standard parameters or headers, you can call client.get_token directly:

+ +
access = client.get_token({
+  grant_type: "client_credentials",
+  audience: "https://api.example.com",
+  headers: {"X-Custom" => "value"},
+  parse: :json, # override parsing
+})
+
+ +

OpenID Connect (OIDC)

+ +
    +
  • If the token response includes an id_token (a JWT), this gem surfaces it in token.params['id_token'].
  • +
  • +Note: This gem does not validate the signature of the id_token. You must use a JWT library (like the jwt gem) and your provider’s JWKs to verify it.
  • +
  • For private_key_jwt client authentication, provide auth_scheme: :private_key_jwt and ensure your key configuration matches the provider requirements.
  • +
  • See OIDC.md for a more complete OIDC overview and examples.
  • +
+ +

Debugging

+ +
    +
  • Set environment variable OAUTH_DEBUG=true to enable verbose Faraday logging (uses the client-provided logger).
  • +
  • To mirror a working curl request, ensure you set the same auth scheme, params, and content type. The Quick Example at the top shows a curl-to-ruby translation.
  • +
+ +
+ +

🦷 FLOSS Funding

+ +

While ruby-oauth tools are free software and will always be, the project would benefit immensely from some funding.
+Raising a monthly budget of… “dollars” would make the project more sustainable.

+ +

We welcome both individual and corporate sponsors! We also offer a
+wide array of funding channels to account for your preferences
+(although currently Open Collective is our preferred funding platform).

+ +

If you’re working in a company that’s making significant use of ruby-oauth tools we’d
+appreciate it if you suggest to your company to become a ruby-oauth sponsor.

+ +

You can support the development of ruby-oauth tools via
+GitHub Sponsors,
+Liberapay,
+PayPal,
+Open Collective
+and Tidelift.

+ + + + + + + + + + + + +
📍 NOTE
If doing a sponsorship in the form of donation is problematic for your company
from an accounting standpoint, we’d recommend the use of Tidelift,
where you can get a support-like subscription instead.
+ +

Open Collective for Individuals

+ +

Support us with a monthly donation and help us continue our activities. [Become a backer]

+ +

NOTE: kettle-readme-backers updates this list every day, automatically.

+ + +

No backers yet. Be the first!
+

+ +

Open Collective for Organizations

+ +

Become a sponsor and get your logo on our README on GitHub with a link to your site. [Become a sponsor]

+ +

NOTE: kettle-readme-backers updates this list every day, automatically.

+ + +

No sponsors yet. Be the first!

+ +

Open Collective for Donors

+ +

Bill Woika
+

+ +

Another way to support open-source

+ +

I’m driven by a passion to foster a thriving open-source community – a space where people can tackle complex problems, no matter how small. Revitalizing libraries that have fallen into disrepair, and building new libraries focused on solving real-world challenges, are my passions. I was recently affected by layoffs, and the tech jobs market is unwelcoming. I’m reaching out here because your support would significantly aid my efforts to provide for my family, and my farm (11 🐔 chickens, 2 🐶 dogs, 3 🐰 rabbits, 8 🐈‍ cats).

+ +

If you work at a company that uses my work, please encourage them to support me as a corporate sponsor. My work on gems you use might show up in bundle fund.

+ +

I’m developing a new library, floss_funding, designed to empower open-source developers like myself to get paid for the work we do, in a sustainable way. Please give it a look.

+ +

Floss-Funding.dev: 👉️ No network calls. 👉️ No tracking. 👉️ No oversight. 👉️ Minimal crypto hashing. 💡 Easily disabled nags

+ +

OpenCollective Backers OpenCollective Sponsors Sponsor Me on Github Liberapay Goal Progress Donate on PayPal Buy me a coffee Donate on Polar Donate to my FLOSS efforts at ko-fi.com Donate to my FLOSS efforts using Patreon

+ +

🔐 Security

+ +

To report a security vulnerability, please use the Tidelift security contact.
+Tidelift will coordinate the fix and disclosure.

+ +

For more see SECURITY.md, THREAT_MODEL.md, and IRP.md.

+ +

🤝 Contributing

+ +

If you need some ideas of where to help, you could work on adding more code coverage,
+or if it is already 💯 (see below) check reek, issues, or PRs,
+or use the gem and think about how it could be better.

+ +

We Keep A Changelog so if you make changes, remember to update it.

+ +

See CONTRIBUTING.md for more detailed instructions.

+ +

🚀 Release Instructions

+ +

See CONTRIBUTING.md.

+ +

Code Coverage

+ +

Coverage Graph

+ +

Coveralls Test Coverage

+ +

QLTY Test Coverage

+ +

🪇 Code of Conduct

+ +

Everyone interacting with this project’s codebases, issue trackers,
+chat rooms and mailing lists agrees to follow the Contributor Covenant 2.1.

+ +

🌈 Contributors

+ +

Contributors

+ +

Made with contributors-img.

+ +

Also see GitLab Contributors: https://gitlab.com/ruby-oauth/oauth2/-/graphs/main

+ +
+ ⭐️ Star History + + + + + + Star History Chart + + + +
+ +

📌 Versioning

+ +

This Library adheres to Semantic Versioning 2.0.0.
+Violations of this scheme should be reported as bugs.
+Specifically, if a minor or patch version is released that breaks backward compatibility,
+a new version should be immediately released that restores compatibility.
+Breaking changes to the public API will only be introduced with new major versions.

+ +
+

dropping support for a platform is both obviously and objectively a breaking change

+—Jordan Harband (@ljharb, maintainer of SemVer) in SemVer issue 716

+
+ +

I understand that policy doesn’t work universally (“exceptions to every rule!”),
+but it is the policy here.
+As such, in many cases it is good to specify a dependency on this library using
+the Pessimistic Version Constraint with two digits of precision.

+ +

For example:

+ +
spec.add_dependency("oauth2", "~> 2.0")
+
+ +
+ 📌 Is "Platform Support" part of the public API? More details inside. + +

SemVer should, IMO, but doesn’t explicitly, say that dropping support for specific Platforms +is a breaking change to an API, and for that reason the bike shedding is endless.

+ +

To get a better understanding of how SemVer is intended to work over a project’s lifetime, +read this article from the creator of SemVer:

+ + + +
+ +

See CHANGELOG.md for a list of releases.

+ +

📄 License

+ +

The gem is available as open source under the terms of
+the MIT License License: MIT.
+See LICENSE.txt for the official Copyright Notice.

+ + + +
    +
  • + Copyright (c) 2017 – 2026 Peter H. Boling, of + + Galtzo.com + + Galtzo.com Logo (Wordless) by Aboling0, CC BY-SA 4.0 + + , and oauth2 contributors. +
  • +
  • + Copyright (c) 2011 - 2013 Michael Bleigh and Intridea, Inc. +
  • +
+ +

🤑 A request for help

+ +

Maintainers have teeth and need to pay their dentists.
+After getting laid off in an RIF in March, and encountering difficulty finding a new one,
+I began spending most of my time building open source tools.
+I’m hoping to be able to pay for my kids’ health insurance this month,
+so if you value the work I am doing, I need your support.
+Please consider sponsoring me or the project.

+ +

To join the community or get help 👇️ Join the Discord.

+ +

Live Chat on Discord

+ +

To say “thanks!” ☝️ Join the Discord or 👇️ send money.

+ +

Sponsor ruby-oauth/oauth2 on Open Source Collective 💌 Sponsor me on GitHub Sponsors 💌 Sponsor me on Liberapay 💌 Donate on PayPal

+ +

Please give the project a star ⭐ ♥.

+ +

Thanks for RTFM. ☺️

+ +
+ + rel="me" Social Proofs + + + + + +
+
+ + + +
+ + diff --git a/docs/js/app.js b/docs/js/app.js index fba274813..f84a8c188 100644 --- a/docs/js/app.js +++ b/docs/js/app.js @@ -1,395 +1,801 @@ -window.__app = function () { - var localStorage = {}, - sessionStorage = {}; - try { - localStorage = window.localStorage; - } catch (e) {} - try { - sessionStorage = window.sessionStorage; - } catch (e) {} - - function createSourceLinks() { - $(".method_details_list .source_code").before( - "[View source]" - ); - $(".toggleSource").toggle( - function () { - $(this).parent().nextAll(".source_code").slideDown(100); - $(this).text("Hide source"); - }, - function () { - $(this).parent().nextAll(".source_code").slideUp(100); - $(this).text("View source"); - } - ); - } - - function createDefineLinks() { - var tHeight = 0; - $(".defines").after(" more..."); - $(".toggleDefines").toggle( - function () { - tHeight = $(this).parent().prev().height(); - $(this).prev().css("display", "inline"); - $(this).parent().prev().height($(this).parent().height()); - $(this).text("(less)"); - }, - function () { - $(this).prev().hide(); - $(this).parent().prev().height(tHeight); - $(this).text("more..."); - } - ); - } - - function createFullTreeLinks() { - var tHeight = 0; - $(".inheritanceTree").toggle( - function () { - tHeight = $(this).parent().prev().height(); - $(this).parent().toggleClass("showAll"); - $(this).text("(hide)"); - $(this).parent().prev().height($(this).parent().height()); - }, - function () { - $(this).parent().toggleClass("showAll"); - $(this).parent().prev().height(tHeight); - $(this).text("show all"); - } - ); - } - - function searchFrameButtons() { - $(".full_list_link").click(function () { - toggleSearchFrame(this, $(this).attr("href")); - return false; - }); - window.addEventListener("message", function (e) { - if (e.data === "navEscape") { - $("#nav").slideUp(100); - $("#search a").removeClass("active inactive"); - $(window).focus(); - } - }); - - $(window).resize(function () { - if ($("#search:visible").length === 0) { - $("#nav").removeAttr("style"); - $("#search a").removeClass("active inactive"); - $(window).focus(); - } - }); - } - - function toggleSearchFrame(id, link) { - var frame = $("#nav"); - $("#search a").removeClass("active").addClass("inactive"); - if (frame.attr("src") === link && frame.css("display") !== "none") { - frame.slideUp(100); - $("#search a").removeClass("active inactive"); - } else { - $(id).addClass("active").removeClass("inactive"); - if (frame.attr("src") !== link) frame.attr("src", link); - frame.slideDown(100); - } - } - - function linkSummaries() { - $(".summary_signature").click(function () { - document.location = $(this).find("a").attr("href"); - }); - } - - function summaryToggle() { - $(".summary_toggle").click(function (e) { - e.preventDefault(); - localStorage.summaryCollapsed = $(this).text(); - $(".summary_toggle").each(function () { - $(this).text($(this).text() == "collapse" ? "expand" : "collapse"); - var next = $(this).parent().parent().nextAll("ul.summary").first(); - if (next.hasClass("compact")) { - next.toggle(); - next.nextAll("ul.summary").first().toggle(); - } else if (next.hasClass("summary")) { - var list = $('