diff --git a/.rubocop.yml b/.rubocop.yml index 6d11146f..ec6a3fb2 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -19,6 +19,7 @@ inherit_mode: AllCops: DisplayCopNames: true # Display the name of the failing cops Exclude: + - 'bin/*' - 'gemfiles/vendor/**/*' - 'vendor/**/*' - '**/.irbrc' diff --git a/.rubocop_gradual.lock b/.rubocop_gradual.lock deleted file mode 100644 index e11e08c0..00000000 --- a/.rubocop_gradual.lock +++ /dev/null @@ -1,27 +0,0 @@ -{ - "bin/bundle:872096170": [ - [66, 5, 20, "ThreadSafety/ClassInstanceVariable: Avoid class instance variables.", 2485198147] - ], - "lib/oauth2.rb:3283430588": [ - [57, 7, 7, "ThreadSafety/ClassInstanceVariable: Avoid class instance variables.", 651502127] - ], - "lib/oauth2/filtered_attributes.rb:3925029601": [ - [13, 5, 63, "Style/ClassMethodsDefinitions: Use `class << self` to define a class method.", 2901108034] - ], - "spec/oauth2/client_spec.rb:1785648507": [ - [207, 15, 20, "RSpec/ContextWording: Context description should match /^when\\b/, /^with\\b/, or /^without\\b/.", 2320605227], - [222, 15, 20, "RSpec/ContextWording: Context description should match /^when\\b/, /^with\\b/, or /^without\\b/.", 1276531672], - [237, 15, 43, "RSpec/ContextWording: Context description should match /^when\\b/, /^with\\b/, or /^without\\b/.", 1383956904], - [252, 15, 43, "RSpec/ContextWording: Context description should match /^when\\b/, /^with\\b/, or /^without\\b/.", 3376202107], - [1175, 17, 12, "RSpec/ContextWording: Context description should match /^when\\b/, /^with\\b/, or /^without\\b/.", 664794325] - ], - "spec/oauth2/error_spec.rb:1692696277": [ - [93, 11, 460, "RSpec/NoExpectationExample: No expectation found in this example.", 3630511675], - [108, 11, 210, "RSpec/NoExpectationExample: No expectation found in this example.", 3948582233], - [240, 11, 534, "RSpec/NoExpectationExample: No expectation found in this example.", 3347340910], - [256, 11, 210, "RSpec/NoExpectationExample: No expectation found in this example.", 3948582233], - [314, 11, 534, "RSpec/NoExpectationExample: No expectation found in this example.", 3347340910], - [375, 11, 534, "RSpec/NoExpectationExample: No expectation found in this example.", 3347340910], - [391, 11, 210, "RSpec/NoExpectationExample: No expectation found in this example.", 3948582233] - ] -} diff --git a/CHANGELOG.md b/CHANGELOG.md index 01e26c92..961b1e91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,8 +20,14 @@ Please file a bug if you notice a violation of semantic versioning. ### 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 +- [gh!707][gh!707] Add `OAuth2::ThingFilter` as the shared filtering primitive used by inspect-time and debug-log filtering 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 + ### Deprecated ### Removed @@ -30,6 +36,11 @@ Please file a bug if you notice a violation of semantic versioning. ### 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. + +[gh!707]: https://github.com/ruby-oauth/oauth2/pull/707 + ## [2.0.18] - 2025-11-08 - TAG: [v2.0.18][2.0.18t] @@ -54,8 +65,6 @@ Please file a bug if you notice a violation of semantic versioning. - [gh!690][gh!690], [gh!691][gh!691], [gh!692][gh!692] - Add yard-fence - handle braces within code fences in markdown properly by @pboling -### Security - [gh!683]: https://github.com/ruby-oauth/oauth2/pull/683 [gh!684]: https://github.com/ruby-oauth/oauth2/pull/684 [gh!685]: https://github.com/ruby-oauth/oauth2/pull/685 @@ -196,8 +205,6 @@ Please file a bug if you notice a violation of semantic versioning. - [gh!660][gh!660] - Links in README (including link to HEAD documentation) by @pboling -### Security - [gh!660]: https://github.com/ruby-oauth/oauth2/pull/660 [gh!657]: https://github.com/ruby-oauth/oauth2/pull/657 [gh!656]: https://github.com/ruby-oauth/oauth2/pull/656 diff --git a/README.md b/README.md index 588a6f16..68486327 100644 --- a/README.md +++ b/README.md @@ -330,6 +330,19 @@ OAuth2.configure do |config| end ``` +Filtering-related settings: + +```ruby +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 diff --git a/docs/OAuth2.html b/docs/OAuth2.html index db795699..e69de29b 100644 --- a/docs/OAuth2.html +++ b/docs/OAuth2.html @@ -1,383 +0,0 @@ - - - - - - - Module: OAuth2 - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Module: OAuth2 - - - -

-
- - - - - - - - - - - -
-
Defined in:
-
lib/oauth2.rb,
- lib/oauth2/error.rb,
lib/oauth2/client.rb,
lib/oauth2/version.rb,
lib/oauth2/response.rb,
lib/oauth2/access_token.rb,
lib/oauth2/authenticator.rb,
lib/oauth2/strategy/base.rb,
lib/oauth2/strategy/implicit.rb,
lib/oauth2/strategy/password.rb,
lib/oauth2/strategy/assertion.rb,
lib/oauth2/strategy/auth_code.rb,
lib/oauth2/filtered_attributes.rb,
lib/oauth2/strategy/client_credentials.rb
-
-
- -
- -

Overview

-
-

:nocov:

- - -
-
-
- - -

Defined Under Namespace

-

- - - Modules: FilteredAttributes, Strategy, Version - - - - Classes: AccessToken, Authenticator, Client, Error, Response - - -

- - -

- Constant Summary - collapse -

- -
- -
OAUTH_DEBUG = -
-
-

When true, enables verbose HTTP logging via Faraday’s logger middleware.
-Controlled by the OAUTH_DEBUG environment variable. Any case-insensitive
-value equal to “true” will enable debugging.

- - -
-
-
- -

Returns:

-
    - -
  • - - - (Boolean) - - - -
  • - -
- -
-
-
ENV.fetch("OAUTH_DEBUG", "false").casecmp("true").zero?
- -
DEFAULT_CONFIG = -
-
-

Default configuration values for the oauth2 library.

- - -
-
-
- -
-

Examples:

- - -

Toggle warnings

-
- -
OAuth2.configure do |config|
-  config[:silence_extra_tokens_warning] = false
-  config[:silence_no_tokens_warning] = false
-end
- -
- -

Returns:

-
    - -
  • - - - (SnakyHash::SymbolKeyed) - - - - — -

    A mutable Hash-like config with symbol keys

    -
    - -
  • - -
- -
-
-
SnakyHash::SymbolKeyed.new(
-  silence_extra_tokens_warning: true,
-  silence_no_tokens_warning: true,
-)
- -
ConnectionError = - -
-
Class.new(Faraday::ConnectionFailed)
- -
TimeoutError = - -
-
Class.new(Faraday::TimeoutError)
- -
- - - - - - - - - -

- Class Method Summary - collapse -

- - - - - - -
-

Class Method Details

- - -
-

- - .configObject - - - - - -

- - - - -
-
-
-
-56
-57
-58
-
-
# File 'lib/oauth2.rb', line 56
-
-def config
-  @config ||= DEFAULT_CONFIG.dup
-end
-
-
- -
-

- - .configure {|config| ... } ⇒ void - - - - - -

-
-

This method returns an undefined value.

Configure global library behavior.

- -

Yields the mutable configuration object so callers can update settings.

- - -
-
-
- -

Yield Parameters:

-
    - -
  • - - config - - - (SnakyHash::SymbolKeyed) - - - - — -

    the configuration object

    -
    - -
  • - -
- -
- - - - -
-
-
-
-66
-67
-68
-
-
# File 'lib/oauth2.rb', line 66
-
-def configure
-  yield config
-end
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Authenticator.html b/docs/OAuth2/Authenticator.html index e0baaca6..e69de29b 100644 --- a/docs/OAuth2/Authenticator.html +++ b/docs/OAuth2/Authenticator.html @@ -1,893 +0,0 @@ - - - - - - - Class: OAuth2::Authenticator - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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 -

- - - - - - - - - - - - - -

Methods included from FilteredAttributes

-

included, #inspect

-
-

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
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Client.html b/docs/OAuth2/Client.html index 32424196..e69de29b 100644 --- a/docs/OAuth2/Client.html +++ b/docs/OAuth2/Client.html @@ -1,2666 +0,0 @@ - - - - - - - Class: OAuth2::Client - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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 -

- - - - - - - - - - - - - -

Methods included from FilteredAttributes

-

included, #inspect

-
-

Constructor Details

- -
-

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

-
-

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

- - -
-
-
-

Parameters:

-
    - -
  • - - client_id - - - (String) - - - - — -

    the client_id value

    -
    - -
  • - -
  • - - client_secret - - - (String) - - - - — -

    the client_secret value

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

    the options to configure the client

    -
    - -
  • - -
- - - - - - - - -

Options Hash (options):

-
    - -
  • - :site - (String) - - - - - —

    the OAuth2 provider site host

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

    absolute or relative URL path to the Authorization endpoint

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

    absolute or relative URL path to the Revoke endpoint

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

    absolute or relative URL path to the Token endpoint

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

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

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

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

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

    Hash of connection options to pass to initialize Faraday

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

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

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

    maximum number of redirects to follow

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

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

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

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

    -
    - -
  • - -
  • - :ssl - (Hash) - - - - - —

    SSL options for Faraday

    -
    - -
  • - -
- - -

Yields:

-
    - -
  • - - - (builder) - - - - — -

    The Faraday connection builder

    -
    - -
  • - -
- -
- - - - -
-
-
-
-50
-51
-52
-53
-54
-55
-56
-57
-58
-59
-60
-61
-62
-63
-64
-65
-66
-67
-68
-69
-70
-71
-
-
# File 'lib/oauth2/client.rb', line 50
-
-def initialize(client_id, client_secret, options = {}, &block)
-  opts = options.dup
-  @id = client_id
-  @secret = client_secret
-  @site = opts.delete(:site)
-  ssl = opts.delete(:ssl)
-  warn("OAuth2::Client#initialize argument `extract_access_token` will be removed in oauth2 v3. Refactor to use `access_token_class`.") if opts[:extract_access_token]
-  @options = {
-    authorize_url: "oauth/authorize",
-    revoke_url: "oauth/revoke",
-    token_url: "oauth/token",
-    token_method: :post,
-    auth_scheme: :basic_auth,
-    connection_opts: {},
-    connection_build: block,
-    max_redirects: 5,
-    raise_errors: true,
-    logger: ::Logger.new($stdout),
-    access_token_class: AccessToken,
-  }.merge(opts)
-  @options[:connection_opts][:ssl] = ssl if ssl
-end
-
-
- -
- -
-

Instance Attribute Details

- - - -
-

- - #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
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Error.html b/docs/OAuth2/Error.html index 7679bdb2..e69de29b 100644 --- a/docs/OAuth2/Error.html +++ b/docs/OAuth2/Error.html @@ -1,782 +0,0 @@ - - - - - - - Exception: OAuth2::Error - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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
-
-
# File 'lib/oauth2/error.rb', line 18
-
-def initialize(response)
-  @response = response
-  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
-
-
- -
- - -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/FilteredAttributes.html b/docs/OAuth2/FilteredAttributes.html index 52a6cd9b..e69de29b 100644 --- a/docs/OAuth2/FilteredAttributes.html +++ b/docs/OAuth2/FilteredAttributes.html @@ -1,345 +0,0 @@ - - - - - - - Module: OAuth2::FilteredAttributes - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Module: OAuth2::FilteredAttributes - - - -

-
- - - - - - - - - -
-
Included in:
-
AccessToken, Authenticator, Client
-
- - - -
-
Defined in:
-
lib/oauth2/filtered_attributes.rb
-
- -
- -

Overview

-
-

Mixin that redacts sensitive instance variables in #inspect output.

- -

Classes include this module and declare which attributes should be filtered
-using filtered_attributes. Any instance variable name that includes one of
-those attribute names will be shown as [FILTERED] in the object’s inspect.

- - -
-
-
- - -

Defined Under Namespace

-

- - - Modules: ClassMethods - - - - -

- - - - - - - - -

- Class Method Summary - collapse -

- - - -

- Instance Method Summary - collapse -

- - - - - - -
-

Class Method Details

- - -
-

- - .included(base) ⇒ void - - - - - -

-
-

This method returns an undefined value.

Hook invoked when the module is included. Extends the including class with
-class-level helpers.

- - -
-
-
-

Parameters:

-
    - -
  • - - base - - - (Class) - - - - — -

    The including class

    -
    - -
  • - -
- - -
- - - - -
-
-
-
-13
-14
-15
-
-
# File 'lib/oauth2/filtered_attributes.rb', line 13
-
-def self.included(base)
-  base.extend(ClassMethods)
-end
-
-
- -
- -
-

Instance Method Details

- - -
-

- - #inspectString - - - - - -

-
-

Custom inspect that redacts configured attributes.

- - -
-
-
- -

Returns:

-
    - -
  • - - - (String) - - - -
  • - -
- -
- - - - -
-
-
-
-56
-57
-58
-59
-60
-61
-62
-63
-64
-65
-66
-67
-68
-
-
# File 'lib/oauth2/filtered_attributes.rb', line 56
-
-def inspect
-  filtered_attribute_names = ClassMethods.filtered_attribute_names(self.class)
-  return super if filtered_attribute_names.empty?
-
-  inspected_vars = instance_variables.map do |var|
-    if filtered_attribute_names.any? { |filtered_var| var.to_s.include?(filtered_var.to_s) }
-      "#{var}=[FILTERED]"
-    else
-      "#{var}=#{instance_variable_get(var).inspect}"
-    end
-  end
-  "#<#{self.class}:#{object_id} #{inspected_vars.join(", ")}>"
-end
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/FilteredAttributes/ClassMethods.html b/docs/OAuth2/FilteredAttributes/ClassMethods.html index 4d8dd37e..e69de29b 100644 --- a/docs/OAuth2/FilteredAttributes/ClassMethods.html +++ b/docs/OAuth2/FilteredAttributes/ClassMethods.html @@ -1,482 +0,0 @@ - - - - - - - Module: OAuth2::FilteredAttributes::ClassMethods - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Module: OAuth2::FilteredAttributes::ClassMethods - - - -

-
- - - - - - - - - - - -
-
Defined in:
-
lib/oauth2/filtered_attributes.rb
-
- -
- -

Overview

-
-

Class-level helpers for configuring filtered attributes.

- - -
-
-
- - -
- - - - - - - -

- Class Method Summary - collapse -

- - - -

- Instance Method Summary - collapse -

- - - - - - -
-

Class Method Details

- - -
-

- - .filtered_attribute_names(base) ⇒ Array<Symbol> - - - - - -

-
-

The configured attribute names to filter.

- - -
-
-
-

Parameters:

-
    - -
  • - - base - - - (Class) - - - - — -

    The class to get filtered attributes for

    -
    - -
  • - -
- -

Returns:

-
    - -
  • - - - (Array<Symbol>) - - - -
  • - -
- -
- - - - -
-
-
-
-32
-33
-34
-
-
# File 'lib/oauth2/filtered_attributes.rb', line 32
-
-def filtered_attribute_names(base)
-  base.instance_variable_get(:@filtered_attribute_names) || []
-end
-
-
- -
-

- - .filtered_attributes(base, *attributes) ⇒ void - - - - - -

-
-

This method returns an undefined value.

Declare attributes that should be redacted in inspect output.

- - -
-
-
-

Parameters:

-
    - -
  • - - attributes - - - (Array<Symbol, String>) - - - - — -

    One or more attribute names

    -
    - -
  • - -
- - -
- - - - -
-
-
-
-24
-25
-26
-
-
# File 'lib/oauth2/filtered_attributes.rb', line 24
-
-def filtered_attributes(base, *attributes)
-  base.instance_variable_set(:@filtered_attribute_names, attributes.map(&:to_sym))
-end
-
-
- -
- -
-

Instance Method Details

- - -
-

- - #filtered_attribute_namesArray<Symbol> - - - - - -

-
-

The configured attribute names to filter.

- - -
-
-
- -

Returns:

-
    - -
  • - - - (Array<Symbol>) - - - -
  • - -
- -
- - - - -
-
-
-
-48
-49
-50
-
-
# File 'lib/oauth2/filtered_attributes.rb', line 48
-
-def filtered_attribute_names
-  ClassMethods.filtered_attribute_names(self)
-end
-
-
- -
-

- - #filtered_attributes(*attributes) ⇒ void - - - - - -

-
-

This method returns an undefined value.

Declare attributes that should be redacted in inspect output.

- - -
-
-
-

Parameters:

-
    - -
  • - - attributes - - - (Array<Symbol, String>) - - - - — -

    One or more attribute names

    -
    - -
  • - -
- - -
- - - - -
-
-
-
-41
-42
-43
-
-
# File 'lib/oauth2/filtered_attributes.rb', line 41
-
-def filtered_attributes(*attributes)
-  ClassMethods.filtered_attributes(self, *attributes)
-end
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Response.html b/docs/OAuth2/Response.html index 4d3aedc7..e69de29b 100644 --- a/docs/OAuth2/Response.html +++ b/docs/OAuth2/Response.html @@ -1,1629 +0,0 @@ - - - - - - - Class: OAuth2::Response - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Strategy.html b/docs/OAuth2/Strategy.html index e4d80de8..e69de29b 100644 --- a/docs/OAuth2/Strategy.html +++ b/docs/OAuth2/Strategy.html @@ -1,117 +0,0 @@ - - - - - - - Module: OAuth2::Strategy - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Module: OAuth2::Strategy - - - -

-
- - - - - - - - - - - -
-
Defined in:
-
lib/oauth2/strategy/base.rb,
- lib/oauth2/strategy/implicit.rb,
lib/oauth2/strategy/password.rb,
lib/oauth2/strategy/assertion.rb,
lib/oauth2/strategy/auth_code.rb,
lib/oauth2/strategy/client_credentials.rb
-
-
- -
- -

Defined Under Namespace

-

- - - - - Classes: Assertion, AuthCode, Base, ClientCredentials, Implicit, Password - - -

- - - - - - - - - -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Strategy/Assertion.html b/docs/OAuth2/Strategy/Assertion.html index 83b0a56b..e69de29b 100644 --- a/docs/OAuth2/Strategy/Assertion.html +++ b/docs/OAuth2/Strategy/Assertion.html @@ -1,491 +0,0 @@ - - - - - - - Class: OAuth2::Strategy::Assertion - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Strategy/AuthCode.html b/docs/OAuth2/Strategy/AuthCode.html index b051aa97..e69de29b 100644 --- a/docs/OAuth2/Strategy/AuthCode.html +++ b/docs/OAuth2/Strategy/AuthCode.html @@ -1,493 +0,0 @@ - - - - - - - Class: OAuth2::Strategy::AuthCode - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Strategy/Base.html b/docs/OAuth2/Strategy/Base.html index 11c634f0..e69de29b 100644 --- a/docs/OAuth2/Strategy/Base.html +++ b/docs/OAuth2/Strategy/Base.html @@ -1,205 +0,0 @@ - - - - - - - Class: OAuth2::Strategy::Base - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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
-
-
- -
- - -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Strategy/ClientCredentials.html b/docs/OAuth2/Strategy/ClientCredentials.html index f233fa6f..e69de29b 100644 --- a/docs/OAuth2/Strategy/ClientCredentials.html +++ b/docs/OAuth2/Strategy/ClientCredentials.html @@ -1,353 +0,0 @@ - - - - - - - Class: OAuth2::Strategy::ClientCredentials - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Class: OAuth2::Strategy::ClientCredentials - - - -

-
- -
-
Inherits:
-
- Base - -
    -
  • Object
  • - - - - - -
- show all - -
-
- - - - - - - - - - - -
-
Defined in:
-
lib/oauth2/strategy/client_credentials.rb
-
- -
- -

Overview

-
-

The Client Credentials Strategy

- - -
-
- - - - - - - - -

- 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) - - - -
  • - -
- -
- - - - -
-
-
-
-12
-13
-14
-
-
# File 'lib/oauth2/strategy/client_credentials.rb', line 12
-
-def authorize_url
-  raise(NotImplementedError, "The authorization endpoint is not used in this strategy")
-end
-
-
- -
-

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

-
-

Retrieve an access token given the specified client.

- - -
-
-
-

Parameters:

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

    additional params

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

    options

    -
    - -
  • - -
- - -
- - - - -
-
-
-
-20
-21
-22
-23
-
-
# File 'lib/oauth2/strategy/client_credentials.rb', line 20
-
-def get_token(params = {}, opts = {})
-  params = params.merge("grant_type" => "client_credentials")
-  @client.get_token(params, opts)
-end
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Strategy/Implicit.html b/docs/OAuth2/Strategy/Implicit.html index 3b12ec0d..e69de29b 100644 --- a/docs/OAuth2/Strategy/Implicit.html +++ b/docs/OAuth2/Strategy/Implicit.html @@ -1,430 +0,0 @@ - - - - - - - Class: OAuth2::Strategy::Implicit - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Strategy/Password.html b/docs/OAuth2/Strategy/Password.html index 819e0946..e69de29b 100644 --- a/docs/OAuth2/Strategy/Password.html +++ b/docs/OAuth2/Strategy/Password.html @@ -1,384 +0,0 @@ - - - - - - - Class: OAuth2::Strategy::Password - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Class: OAuth2::Strategy::Password - - - -

-
- -
-
Inherits:
-
- Base - -
    -
  • Object
  • - - - - - -
- show all - -
-
- - - - - - - - - - - -
-
Defined in:
-
lib/oauth2/strategy/password.rb
-
- -
- -

Overview

-
-

The Resource Owner Password Credentials Authorization Strategy

- -

IMPORTANT (OAuth 2.1): The Resource Owner Password Credentials grant is omitted in OAuth 2.1.
-It remains here for backward compatibility with OAuth 2.0 providers. Prefer Authorization Code + PKCE.

- -

References:

-
    -
  • OAuth 2.1 draft: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13
  • -
  • Okta explainer: https://developer.okta.com/blog/2019/12/13/oauth-2-1-how-many-rfcs
  • -
  • FusionAuth blog: https://fusionauth.io/blog/2020/04/15/whats-new-in-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_urlObject - - - - - -

-
-

Not used for this strategy

- - -
-
-
- -

Raises:

-
    - -
  • - - - (NotImplementedError) - - - -
  • - -
- -
- - - - -
-
-
-
-20
-21
-22
-
-
# File 'lib/oauth2/strategy/password.rb', line 20
-
-def authorize_url
-  raise(NotImplementedError, "The authorization endpoint is not used in this strategy")
-end
-
-
- -
-

- - #get_token(username, password, params = {}, opts = {}) ⇒ Object - - - - - -

-
-

Retrieve an access token given the specified End User username and password.

- - -
-
-
-

Parameters:

-
    - -
  • - - username - - - (String) - - - - — -

    the End User username

    -
    - -
  • - -
  • - - password - - - (String) - - - - — -

    the End User password

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

    additional params

    -
    - -
  • - -
- - -
- - - - -
-
-
-
-29
-30
-31
-32
-33
-34
-35
-36
-
-
# File 'lib/oauth2/strategy/password.rb', line 29
-
-def get_token(username, password, params = {}, opts = {})
-  params = {
-    "grant_type" => "password",
-    "username" => username,
-    "password" => password,
-  }.merge(params)
-  @client.get_token(params, opts)
-end
-
-
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/OAuth2/Version.html b/docs/OAuth2/Version.html index 19966458..e69de29b 100644 --- a/docs/OAuth2/Version.html +++ b/docs/OAuth2/Version.html @@ -1,121 +0,0 @@ - - - - - - - Module: OAuth2::Version - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Module: OAuth2::Version - - - -

-
- - - - - - - - - - - -
-
Defined in:
-
lib/oauth2/version.rb
-
- -
- - - -

- Constant Summary - collapse -

- -
- -
VERSION = - -
-
"2.0.18"
- -
- - - - - - - - - - -
- - - -
- - \ No newline at end of file diff --git a/docs/_index.html b/docs/_index.html index caafcc49..e69de29b 100644 --- a/docs/_index.html +++ b/docs/_index.html @@ -1,358 +0,0 @@ - - - - - - - Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Documentation by YARD 0.9.38

-
-

Alphabetic Index

- -

File Listing

- - -
-

Namespace Listing A-Z

- - - - - - - - -
- - - - - -
    -
  • B
  • -
      - -
    • - Base - - (OAuth2::Strategy) - -
    • - -
    -
- - - - - -
    -
  • E
  • -
      - -
    • - Error - - (OAuth2) - -
    • - -
    -
- - - - - -
    -
  • I
  • -
      - -
    • - Implicit - - (OAuth2::Strategy) - -
    • - -
    -
- - -
    -
  • O
  • - -
- - -
- - -
    -
  • P
  • -
      - -
    • - Password - - (OAuth2::Strategy) - -
    • - -
    -
- - -
    -
  • R
  • - -
- - -
    -
  • S
  • - -
- - -
    -
  • V
  • -
      - -
    • - Version - - (OAuth2) - -
    • - -
    -
- -
- -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/class_list.html b/docs/class_list.html index df1ca243..e69de29b 100644 --- a/docs/class_list.html +++ b/docs/class_list.html @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - Class List - - - -
-
-

Class List

- - - -
- - -
- - diff --git a/docs/file.CHANGELOG.html b/docs/file.CHANGELOG.html index b2947ec3..e69de29b 100644 --- a/docs/file.CHANGELOG.html +++ b/docs/file.CHANGELOG.html @@ -1,1332 +0,0 @@ - - - - - - - File: CHANGELOG - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Changelog

- -

SemVer 2.0.0 Keep-A-Changelog 1.0.0

- -

All notable changes to this project will be documented in this file.

- -

The format is based on Keep a Changelog,
-and this project adheres to Semantic Versioning,
-and yes, platform and engine support are part of the public API.
-Please file a bug if you notice a violation of semantic versioning.

- -

Unreleased

- -

Added

- -

Changed

- -

Deprecated

- -

Removed

- -

Fixed

- -

Security

- -

-2.0.18 - 2025-11-08

- -
    -
  • TAG: v2.0.18 -
  • -
  • COVERAGE: 100.00% – 526/526 lines in 14 files
  • -
  • BRANCH COVERAGE: 100.00% – 178/178 branches in 14 files
  • -
  • 90.48% documented
  • -
- -

Added

- -
    -
  • -gh!683, gh!684 - Improve documentation by @pboling
  • -
  • -gh!686- Add Incident Response Plan by @pboling
  • -
  • -gh!687- Add Threat Model by @pboling
  • -
- -

Changed

- -
    -
  • -gh!685 - upgrade kettle-dev v1.1.24 by @pboling
  • -
  • upgrade kettle-dev v1.1.52 by @pboling -
      -
    • Add open collective donors to README
    • -
    -
  • -
- -

Fixed

- -
    -
  • -gh!690, gh!691, gh!692 - Add yard-fence -
      -
    • handle braces within code fences in markdown properly by @pboling
    • -
    -
  • -
- -

Security

- -

-2.0.17 - 2025-09-15

- -
    -
  • TAG: v2.0.17 -
  • -
  • COVERAGE: 100.00% – 526/526 lines in 14 files
  • -
  • BRANCH COVERAGE: 100.00% – 178/178 branches in 14 files
  • -
  • 90.48% documented
  • -
- -

Added

- -
    -
  • -gh!682 - AccessToken: support Hash-based verb-dependent token transmission mode (e.g., {get: :query, post: :header})
  • -
- -

-2.0.16 - 2025-09-14

- -
    -
  • TAG: v2.0.16 -
  • -
  • COVERAGE: 100.00% – 520/520 lines in 14 files
  • -
  • BRANCH COVERAGE: 100.00% – 176/176 branches in 14 files
  • -
  • 90.48% documented
  • -
- -

Added

- -
    -
  • -gh!680 - E2E example using mock test server added in v2.0.11 by @pboling -
      -
    • mock-oauth2-server upgraded to v2.3.0 -
        -
      • https://github.com/navikt/mock-oauth2-server
      • -
      -
    • -
    • docker compose -f docker-compose-ssl.yml up -d --wait
    • -
    • ruby examples/e2e.rb
    • -
    • docker compose -f docker-compose-ssl.yml down
    • -
    • mock server readiness wait is 90s
    • -
    • override via E2E_WAIT_TIMEOUT
    • -
    -
  • -
  • -gh!676, gh!679 - Apache SkyWalking Eyes dependency license check by @pboling
  • -
- -

Changed

- -
    -
  • -gh!678 - Many improvements to make CI more resilient (past/future proof) by @pboling
  • -
  • -gh!681 - Upgrade to kettle-dev v1.1.19
  • -
- -

-2.0.15 - 2025-09-08

- -
    -
  • TAG: v2.0.15 -
  • -
  • COVERAGE: 100.00% – 519/519 lines in 14 files
  • -
  • BRANCH COVERAGE: 100.00% – 174/174 branches in 14 files
  • -
  • 90.48% documented
  • -
- -

Added

- -
    -
  • -gh!671 - Complete documentation example for Instagram by @pboling
  • -
  • .env.local.example for contributor happiness
  • -
  • note lack of builds for JRuby 9.2, 9.3 & Truffleruby 22.3, 23.0 - -
  • -
  • -gh!670 - AccessToken: verb-dependent token transmission mode by @mrj -
      -
    • e.g., Instagram GET=:query, POST/DELETE=:header
    • -
    -
  • -
- -

Changed

- -
    -
  • -gh!669 - Upgrade to kettle-dev v1.1.9 by @pboling
  • -
- -

Fixed

- -
    -
  • Remove accidentally duplicated lines, and fix typos in CHANGELOG.md
  • -
  • point badge to the correct workflow for Ruby 2.3 (caboose.yml)
  • -
- -

-2.0.14 - 2025-08-31

- -
    -
  • TAG: v2.0.14 -
  • -
  • COVERAGE: 100.00% – 519/519 lines in 14 files
  • -
  • BRANCH COVERAGE: 100.00% – 174/174 branches in 14 files
  • -
  • 90.48% documented
  • -
- -

Added

- -
    -
  • improved documentation by @pboling
  • -
  • -gh!665 - Document Mutual TLS (mTLS) usage with example in README (connection_opts.ssl client_cert/client_key and auth_scheme: :tls_client_auth) by @pboling
  • -
  • -gh!666 - Document usage of flat query params using Faraday::FlatParamsEncoder, with example URI, in README by @pboling -
      -
    • Spec: verify flat params are preserved with Faraday::FlatParamsEncoder (skips on Faraday without FlatParamsEncoder)
    • -
    -
  • -
  • -gh!662 - documentation notes in code comments and README highlighting OAuth 2.1 differences, with references, by @pboling -
      -
    • PKCE required for auth code,
    • -
    • exact redirect URI match,
    • -
    • implicit/password grants omitted,
    • -
    • avoid bearer tokens in query,
    • -
    • refresh token guidance for public clients,
    • -
    • simplified client definitions
    • -
    -
  • -
  • -gh!663 - document how to implement an OIDC client with this gem in OIDC.md by @pboling -
      -
    • also, list libraries built on top of the oauth2 gem that implement OIDC
    • -
    -
  • -
  • -gh!664 - README: Add example for JHipster UAA (Spring Cloud) password grant, converted from Postman/Net::HTTP by @pboling
  • -
- -

-2.0.13 - 2025-08-30

- -
    -
  • TAG: v2.0.13 -
  • -
  • COVERAGE: 100.00% – 519/519 lines in 14 files
  • -
  • BRANCH COVERAGE: 100.00% – 174/174 branches in 14 files
  • -
  • 90.48% documented
  • -
- -

Added

- -
    -
  • -gh!656 - Support revocation with URL-encoded parameters
  • -
  • -gh!660 - Inline yard documentation by @pboling
  • -
  • -gh!660 - Complete RBS types documentation by @pboling
  • -
  • -gh!660- (more) Comprehensive documentation / examples by @pboling
  • -
  • -gh!657 - Updated documentation for org-rename by @pboling
  • -
  • More funding links by @Aboling0
  • -
  • Documentation: Added docs/OIDC.md with OIDC 1.0 overview, example, and references
  • -
- -

Changed

- -
    -
  • Upgrade Code of Conduct to Contributor Covenant 2.1 by @pboling
  • -
  • -gh!660 - Shrink post-install message by 4 lines by @pboling
  • -
- -

Fixed

- -
    -
  • -gh!660 - Links in README (including link to HEAD documentation) by @pboling
  • -
- -

Security

- -

-2.0.12 - 2025-05-31

- -
    -
  • TAG: v2.0.12 -
  • -
  • Line Coverage: 100.0% (520 / 520)
  • -
  • Branch Coverage: 100.0% (174 / 174)
  • -
  • 80.00% documented
  • -
- -

Added

- -
    -
  • -gh!652 - Support IETF rfc7515 JSON Web Signature - JWS by @mridang -
      -
    • Support JWT kid for key discovery and management
    • -
    -
  • -
  • More Documentation by @pboling -
      -
    • Documented Serialization Extensions
    • -
    • Added Gatzo.com FLOSS logo by @Aboling0, CC BY-SA 4.0
    • -
    -
  • -
  • Documentation site @ https://oauth2.galtzo.com now complete
  • -
- -

Changed

- -
    -
  • Updates to gemspec (email, funding url, post install message)
  • -
- -

Fixed

- -
    -
  • Documentation Typos by @pboling
  • -
- -

-2.0.11 - 2025-05-23

- -
    -
  • TAG: v2.0.11 -
  • -
  • COVERAGE: 100.00% – 518/518 lines in 14 files
  • -
  • BRANCH COVERAGE: 100.00% – 172/172 branches in 14 files
  • -
  • 80.00% documented
  • -
- -

Added

- -
    -
  • -gh!651 - :snaky_hash_klass option (@pboling)
  • -
  • More documentation
  • -
  • Codeberg as ethical mirror (@pboling) -
      -
    • https://codeberg.org/ruby-oauth/oauth2
    • -
    -
  • -
  • Don’t check for cert if SKIP_GEM_SIGNING is set (@pboling)
  • -
  • All runtime deps, including oauth-xx sibling gems, are now tested against HEAD (@pboling)
  • -
  • All runtime deps, including ruby-oauth sibling gems, are now tested against HEAD (@pboling)
  • -
  • YARD config, GFM compatible with relative file links (@pboling)
  • -
  • Documentation site on GitHub Pages (@pboling) - -
  • -
  • -!649 - Test compatibility with all key minor versions of Hashie v0, v1, v2, v3, v4, v5, HEAD (@pboling)
  • -
  • -gh!651 - Mock OAuth2 server for testing (@pboling) -
      -
    • https://github.com/navikt/mock-oauth2-server
    • -
    -
  • -
- -

Changed

- -
    -
  • -gh!651 - Upgraded to snaky_hash v2.0.3 (@pboling) -
      -
    • Provides solution for serialization issues
    • -
    -
  • -
  • Updated spec.homepage_uri in gemspec to GitHub Pages YARD documentation site (@pboling)
  • -
- -

Fixed

- -
    -
  • -gh!650 - Regression in return type of OAuth2::Response#parsed (@pboling)
  • -
  • Incorrect documentation related to silencing warnings (@pboling)
  • -
- -

-2.0.10 - 2025-05-17

- -
    -
  • TAG: v2.0.10 -
  • -
  • COVERAGE: 100.00% – 518/518 lines in 14 files
  • -
  • BRANCH COVERAGE: 100.00% – 170/170 branches in 14 files
  • -
  • 79.05% documented
  • -
- -

Added

- -
    -
  • -gh!632 - Added funding.yml (@Aboling0)
  • -
  • -!635 - Added .gitlab-ci.yml (@jessieay)
  • -
  • -#638 - Documentation of support for ILO Fundamental Principles of Rights at Work (@pboling)
  • -
  • -!642 - 20-year certificate for signing gem releases, expires 2045-04-29 (@pboling) -
      -
    • Gemspec metadata -
        -
      • funding_uri
      • -
      • news_uri
      • -
      • mailing_list_uri
      • -
      -
    • -
    • SHA256 and SHA512 Checksums for release
    • -
    -
  • -
  • -!643 - Add token_name option (@pboling) -
      -
    • Specify the parameter name that identifies the access token
    • -
    -
  • -
  • -!645 - Add OAuth2::OAUTH_DEBUG constant, based on `ENV[“OAUTH_DEBUG”] (@pboling)
  • -
  • -!646 - Add OAuth2.config.silence_extra_tokens_warning, default: false (@pboling)
  • -
  • -!647 - Add IETF RFC 7009 Token Revocation compliant (@pboling) -
      -
    • OAuth2::Client#revoke_token
    • -
    • OAuth2::AccessToken#revoke
    • -
    • See: https://datatracker.ietf.org/doc/html/rfc7009
    • -
    -
  • -
  • -gh!644, gh!645 - Added CITATION.cff (@Aboling0)
  • -
  • -!648 - Improved documentation (@pboling)
  • -
- -

Changed

- -
    -
  • Default value of OAuth2.config.silence_extra_tokens_warning was false, now true (@pboling)
  • -
  • Gem releases are now cryptographically signed, with a 20-year cert (@pboling) -
      -
    • Allow linux distros to build release without signing, as their package managers sign independently
    • -
    -
  • -
  • -!647 - OAuth2::AccessToken#refresh now supports block param pass through (@pboling)
  • -
  • -!647 - OAuth2.config is no longer writable (@pboling)
  • -
  • -!647 - Errors raised by OAuth2::AccessToken are now always OAuth2::Error and have better metadata (@pboling)
  • -
- -

Fixed

- -
    -
  • -#95 - restoring an access token via AccessToken#from_hash (@pboling) -
      -
    • This was a 13 year old bug report. 😘
    • -
    -
  • -
  • -#619 - Internal options (like snaky, raise_errors, and parse) are no longer included in request (@pboling)
  • -
  • -!633 - Spaces will now be encoded as %20 instead of + (@nov.matake)
  • -
  • -!634 - CHANGELOG.md documentation fix (@skuwa229)
  • -
  • -!638 - fix expired? when expires_in is 0 (@disep)
  • -
  • -!639 - Only instantiate OAuth2::Error if raise_errors option is true (@glytch2)
  • -
  • -#639 - AccessToken#to_hash is now serializable, just a regular Hash (@pboling)
  • -
  • -!640 - README.md documentation fix (@martinezcoder)
  • -
  • -!641 - Do not include sensitive information in the inspect (@manuelvanrijn)
  • -
  • -#641 - Made default JSON response parser more resilient (@pboling)
  • -
  • -#645 - Response no longer becomes a snaky hash (@pboling)
  • -
  • -gh!646 - Change require to require_relative (improve performance) (@Aboling0)
  • -
- -

-2.0.9 - 2022-09-16

- - - -

Added

- -
    -
  • More specs (@pboling)
  • -
- -

Changed

- -
    -
  • Complete migration to main branch as default (@pboling)
  • -
  • Complete migration to Gitlab, updating all links, and references in VCS-managed files (@pboling)
  • -
- -

-2.0.8 - 2022-09-01

- - - -

Changed

- -
    -
  • -!630 - Extract snaky_hash to external dependency (@pboling)
  • -
- -

Added

- -
    -
  • -!631 - New global configuration option OAuth2.config.silence_extra_tokens_warning (default: false) fixes #628 -
  • -
- -

-2.0.7 - 2022-08-22

- - - -

Added

- -
    -
  • -!629 - Allow POST of JSON to get token (@pboling, @terracatta)
  • -
- -

Fixed

- -
    -
  • -!626 - Fixes a regression in 2.0.6. Will now prefer the key order from the lookup, not the hash keys (@rickselby) -
      -
    • Note: This fixes compatibility with omniauth-oauth2 and AWS
    • -
    -
  • -
  • -!625 - Fixes the printed version in the post install message (@hasghari)
  • -
- -

-2.0.6 - 2022-07-13

- - - -

Fixed

- -
    -
  • -!624 - Fixes a regression in v2.0.5, where an error would be raised in refresh_token flows due to (legitimate) lack of access_token (@pboling)
  • -
- -

-2.0.5 - 2022-07-07

- - - -

Fixed

- -
    -
  • -!620 - Documentation improvements, to help with upgrading (@swanson)
  • -
  • -!621 - Fixed #528 and #619 (@pboling) -
      -
    • All data in responses is now returned, with the access token removed and set as token -
        -
      • -refresh_token is no longer dropped
      • -
      • -BREAKING: Microsoft’s id_token is no longer left as access_token['id_token'], but moved to the standard access_token.token that all other strategies use
      • -
      -
    • -
    • Remove parse and snaky from options so they don’t get included in response
    • -
    • There is now 100% test coverage, for lines and branches, and it will stay that way.
    • -
    -
  • -
- -

-2.0.4 - 2022-07-01

- - - -

Fixed

- -
    -
  • -!618 - In some scenarios the snaky option default value was not applied (@pboling)
  • -
- -

-2.0.3 - 2022-06-28

- - - -

Added

- -
    -
  • -!611 - Proper deprecation warnings for extract_access_token argument (@pboling)
  • -
  • -!612 - Add snaky: false option to skip conversion to OAuth2::SnakyHash (default: true) (@pboling)
  • -
- -

Fixed

- -
    -
  • -!608 - Wrap Faraday::TimeoutError in OAuth2::TimeoutError (@nbibler)
  • -
  • -!615 - Fix support for requests with blocks, see Faraday::Connection#run_request (@pboling)
  • -
- -

-2.0.2 - 2022-06-24

- - - -

Fixed

- -
    -
  • -!604 - Wrap Faraday::TimeoutError in OAuth2::TimeoutError (@stanhu)
  • -
  • -!606 - Ruby 2.7 deprecation warning fix: Move access_token_class parameter into Client constructor (@stanhu)
  • -
  • -!607 - CHANGELOG correction, reference to OAuth2::ConnectionError (@zavan)
  • -
- -

-2.0.1 - 2022-06-22

- - - -

Added

- -
    -
  • Documentation improvements (@pboling)
  • -
  • Increased test coverage to 99% (@pboling)
  • -
- -

-2.0.0 - 2022-06-21

- - - -

Added

- -
    -
  • -!158, !344 - Optionally pass raw response to parsers (@niels)
  • -
  • -!190, !332, !334, !335, !360, !426, !427, !461 - Documentation (@josephpage, @pboling, @meganemura, @joshRpowell, @elliotcm)
  • -
  • -!220 - Support IETF rfc7523 JWT Bearer Tokens Draft 04+ (@jhmoore)
  • -
  • -!298 - Set the response object on the access token on Client#get_token for debugging (@cpetschnig)
  • -
  • -!305 - Option: OAuth2::Client#get_token - :access_token_class (AccessToken); user specified class to use for all calls to get_token (@styd)
  • -
  • -!346 - Modern gem structure (@pboling)
  • -
  • -!351 - Support Jruby 9k (@pboling)
  • -
  • -!362 - Support SemVer release version scheme (@pboling)
  • -
  • -!363 - New method OAuth2::AccessToken#refresh! same as old refresh, with backwards compatibility alias (@pboling)
  • -
  • -!364 - Support application/hal+json format (@pboling)
  • -
  • -!365 - Support application/vnd.collection+json format (@pboling)
  • -
  • -!376 - Documentation: Example / Test for Google 2-legged JWT (@jhmoore)
  • -
  • -!381 - Spec for extra header params on client credentials (@nikz)
  • -
  • -!394 - Option: OAuth2::AccessToken#initialize - :expires_latency (nil); number of seconds by which AccessToken validity will be reduced to offset latency (@klippx)
  • -
  • -!412 - Support application/vdn.api+json format (from jsonapi.org) (@david-christensen)
  • -
  • -!413 - Documentation: License scan and report (@meganemura)
  • -
  • -!442 - Option: OAuth2::Client#initialize - :logger (::Logger.new($stdout)) logger to use when OAUTH_DEBUG is enabled (for parity with 1-4-stable branch) (@rthbound)
  • -
  • -!494 - Support OIDC 1.0 Private Key JWT; based on the OAuth JWT assertion specification (RFC 7523) (@SteveyblamWork)
  • -
  • -!549 - Wrap Faraday::ConnectionFailed in OAuth2::ConnectionError (@nikkypx)
  • -
  • -!550 - Raise error if location header not present when redirecting (@stanhu)
  • -
  • -!552 - Add missing version.rb require (@ahorek)
  • -
  • -!553 - Support application/problem+json format (@janz93)
  • -
  • -!560 - Support IETF rfc6749, section 2.3.1 - don’t set auth params when nil (@bouk)
  • -
  • -!571 - Support Ruby 3.1 (@pboling)
  • -
  • -!575 - Support IETF rfc7231, section 7.1.2 - relative location in redirect (@pboling)
  • -
  • -!581 - Documentation: of breaking changes (@pboling)
  • -
- -

Changed

- -
    -
  • -!191 - BREAKING: Token is expired if expired_at time is now (@davestevens)
  • -
  • -!312 - BREAKING: Set :basic_auth as default for :auth_scheme instead of :request_body. This was default behavior before 1.3.0. (@tetsuya, @wy193777)
  • -
  • -!317 - Dependency: Upgrade jwt to 2.x.x (@travisofthenorth)
  • -
  • -!338 - Dependency: Switch from Rack::Utils.escape to CGI.escape (@josephpage)
  • -
  • -!339, !368, !424, !479, !493, !539, !542, !553 - CI Updates, code coverage, linting, spelling, type fixes, New VERSION constant (@pboling, @josephpage, @ahorek)
  • -
  • -!410 - BREAKING: Removed the ability to call .error from an OAuth2::Response object (@jhmoore)
  • -
  • -!414 - Use Base64.strict_encode64 instead of custom internal logic (@meganemura)
  • -
  • -!469 - BREAKING: Default value for option OAuth2::Client - :authorize_url removed leading slash to work with relative paths by default ('oauth/authorize') (@ghost)
  • -
  • -!469 - BREAKING: Default value for option OAuth2::Client - :token_url removed leading slash to work with relative paths by default ('oauth/token') (@ghost)
  • -
  • -!507, !575 - BREAKING: Transform keys to snake case, always, by default (ultimately via rash_alt gem) -
      -
    • Original keys will still work as previously, in most scenarios, thanks to rash_alt gem.
    • -
    • However, this is a breaking change if you rely on response.parsed.to_h, 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.
    • -
    -
  • -
  • -!576 - BREAKING: Stop rescuing parsing errors (@pboling)
  • -
  • -!591 - DEPRECATION: OAuth2::Client - :extract_access_token option is deprecated
  • -
- -

Fixed

- -
    -
  • -!158, !344 - Handling of errors when using omniauth-facebook (@niels)
  • -
  • -!294 - Fix: “Unexpected middleware set” issue with Faraday when OAUTH_DEBUG=true (@spectator, @gafrom)
  • -
  • -!300 - Documentation: Oauth2::Error - Error codes are strings, not symbols (@NobodysNightmare)
  • -
  • -!318, !326, !343, !347, !397, !464, !561, !565 - Dependency: Support all versions of faraday (see gemfiles/README.md for compatibility matrix with Ruby engines & versions) (@pboling, @raimondasv, @zacharywelch, @Fudoshiki, @ryogift, @sj26, @jdelStrother)
  • -
  • -!322, !331, !337, !361, !371, !377, !383, !392, !395, !400, !401, !403, !415, !567 - Updated Rubocop, Rubocop plugins and improved code style (@pboling, @bquorning, @lautis, @spectator)
  • -
  • -!328 - Documentation: Homepage URL is SSL (@amatsuda)
  • -
  • -!339, !479 - Update testing infrastructure for all supported Rubies (@pboling and @josephpage)
  • -
  • -!366 - Security: Fix logging to $stdout of request and response bodies via Faraday’s logger and ENV["OAUTH_DEBUG"] == 'true' (@pboling)
  • -
  • -!380 - Fix: Stop attempting to encode non-encodable objects in Oauth2::Error (@jhmoore)
  • -
  • -!399 - Fix: Stop duplicating redirect_uri in get_token (@markus)
  • -
  • -!410 - Fix: SystemStackError caused by circular reference between Error and Response classes (@jhmoore)
  • -
  • -!460 - Fix: Stop throwing errors when raise_errors is set to false; analog of !524 for 1-4-stable branch (@joaolrpaulo)
  • -
  • -!472 - Security: Add checks to enforce client_secret is never passed in authorize_url query params for implicit and auth_code grant types (@dfockler)
  • -
  • -!482 - Documentation: Update last of intridea links to ruby-oauth (@pboling)
  • -
  • -!536 - Security: Compatibility with more (and recent) Ruby OpenSSL versions, Github Actions, Rubocop updated, analogous to !535 on 1-4-stable branch (@pboling)
  • -
  • -!595 - Graceful handling of empty responses from Client#get_token, respecting :raise_errors config (@stanhu)
  • -
  • -!596 - Consistency between AccessToken#refresh and Client#get_token named arguments (@stanhu)
  • -
  • -!598 - Fix unparseable data not raised as error in Client#get_token, respecting :raise_errors config (@stanhu)
  • -
- -

Removed

- -
    -
  • -!341 - Remove Rdoc & Jeweler related files (@josephpage)
  • -
  • -!342 - BREAKING: Dropped support for Ruby 1.8 (@josephpage)
  • -
  • -!539 - Remove reliance on globally included OAuth2 in tests, analog of !538 for 1-4-stable (@anderscarling)
  • -
  • -!566 - Dependency: Removed wwtd (@bquorning)
  • -
  • -!589, !593 - Remove support for expired MAC token draft spec (@stanhu)
  • -
  • -!590 - Dependency: Removed multi_json (@stanhu)
  • -
- -

-1.4.11 - 2022-09-16

- -
    -
  • TAG: v1.4.11 -
  • -
  • Complete migration to main branch as default (@pboling)
  • -
  • Complete migration to Gitlab, updating all links, and references in VCS-managed files (@pboling)
  • -
- -

-1.4.10 - 2022-07-01

- -
    -
  • TAG: v1.4.10 -
  • -
  • FIPS Compatibility !587 (@akostadinov)
  • -
- -

-1.4.9 - 2022-02-20

- -
    -
  • TAG: v1.4.9 -
  • -
  • Fixes compatibility with Faraday v2 572 -
  • -
  • Includes supported versions of Faraday in test matrix: -
      -
    • Faraday ~> 2.2.0 with Ruby >= 2.6
    • -
    • Faraday ~> 1.10 with Ruby >= 2.4
    • -
    • Faraday ~> 0.17.3 with Ruby >= 1.9
    • -
    -
  • -
  • Add Windows and MacOS to test matrix
  • -
- -

-1.4.8 - 2022-02-18

- -
    -
  • TAG: v1.4.8 -
  • -
  • MFA is now required to push new gem versions (@pboling)
  • -
  • README overhaul w/ new Ruby Version and Engine compatibility policies (@pboling)
  • -
  • -!569 Backport fixes (!561 by @ryogift), and add more fixes, to allow faraday 1.x and 2.x (@jrochkind)
  • -
  • Improve Code Coverage tracking (Coveralls, CodeCov, CodeClimate), and enable branch coverage (@pboling)
  • -
  • Add CodeQL, Security Policy, Funding info (@pboling)
  • -
  • Added Ruby 3.1, jruby, jruby-head, truffleruby, truffleruby-head to build matrix (@pboling)
  • -
  • -!543 - Support for more modern Open SSL libraries (@pboling)
  • -
- -

-1.4.7 - 2021-03-19

- -
    -
  • TAG: v1.4.7 -
  • -
  • -!541 - Backport fix to expires_at handling !533 to 1-4-stable branch. (@dobon)
  • -
- -

-1.4.6 - 2021-03-19

- -
    -
  • TAG: v1.4.6 -
  • -
  • -!540 - Add VERSION constant (@pboling)
  • -
  • -!537 - Fix crash in OAuth2::Client#get_token (@anderscarling)
  • -
  • -!538 - Remove reliance on globally included OAuth2 in tests, analogous to !539 on main branch (@anderscarling)
  • -
- -

-1.4.5 - 2021-03-18

- -
    -
  • TAG: v1.4.5 -
  • -
  • -!535 - Compatibility with range of supported Ruby OpenSSL versions, Rubocop updates, Github Actions, analogous to !536 on main branch (@pboling)
  • -
  • -!518 - Add extract_access_token option to OAuth2::Client (@jonspalmer)
  • -
  • -!507 - Fix camel case content type, response keys (@anvox)
  • -
  • -!500 - Fix YARD documentation formatting (@olleolleolle)
  • -
- -

-1.4.4 - 2020-02-12

- -
    -
  • TAG: v1.4.4 -
  • -
  • -!408 - Fixed expires_at for formatted time (@Lomey)
  • -
- -

-1.4.3 - 2020-01-29

- -
    -
  • TAG: v1.4.3 -
  • -
  • -!483 - add project metadata to gemspec (@orien)
  • -
  • -!495 - support additional types of access token requests (@SteveyblamFreeagent, @thomcorley, @dgholz) -
      -
    • Adds support for private_key_jwt and tls_client_auth
    • -
    -
  • -
  • -!433 - allow field names with square brackets and numbers in params (@asm256)
  • -
- -

-1.4.2 - 2019-10-01

- -
    -
  • TAG: v1.4.2 -
  • -
  • -!478 - support latest version of faraday & fix build (@pboling) -
      -
    • Officially support Ruby 2.6 and truffleruby
    • -
    -
  • -
- -

-1.4.1 - 2018-10-13

- -
    -
  • TAG: v1.4.1 -
  • -
  • -!417 - update jwt dependency (@thewoolleyman)
  • -
  • -!419 - remove rubocop dependency (temporary, added back in !423) (@pboling)
  • -
  • -!418 - update faraday dependency (@pboling)
  • -
  • -!420 - update oauth2.gemspec (@pboling)
  • -
  • -!421 - fix CHANGELOG.md for previous releases (@pboling)
  • -
  • -!422 - update LICENSE and README.md (@pboling)
  • -
  • -!423 - update builds, Rakefile (@pboling) -
      -
    • officially document supported Rubies -
        -
      • Ruby 1.9.3
      • -
      • Ruby 2.0.0
      • -
      • Ruby 2.1
      • -
      • Ruby 2.2
      • -
      • -JRuby 1.7 (targets MRI v1.9)
      • -
      • -JRuby 9.0 (targets MRI v2.0)
      • -
      • Ruby 2.3
      • -
      • Ruby 2.4
      • -
      • Ruby 2.5
      • -
      • -JRuby 9.1 (targets MRI v2.3)
      • -
      • -JRuby 9.2 (targets MRI v2.5)
      • -
      -
    • -
    -
  • -
- -

-1.4.0 - 2017-06-09

- -
    -
  • TAG: v1.4.0 -
  • -
  • Drop Ruby 1.8.7 support (@sferik)
  • -
  • Fix some RuboCop offenses (@sferik)
  • -
  • -Dependency: Remove Yardstick (@sferik)
  • -
  • -Dependency: Upgrade Faraday to 0.12 (@sferik)
  • -
- -

-1.3.1 - 2017-03-03

- -
    -
  • TAG: v1.3.1 -
  • -
  • Add support for Ruby 2.4.0 (@pschambacher)
  • -
  • -Dependency: Upgrade Faraday to Faraday 0.11 (@mcfiredrill, @rhymes, @pschambacher)
  • -
- -

-1.3.0 - 2016-12-28

- -
    -
  • TAG: v1.3.0 -
  • -
  • Add support for header-based authentication to the Client so it can be used across the library (@bjeanes)
  • -
  • Default to header-based authentication when getting a token from an authorisation code (@maletor)
  • -
  • -Breaking: Allow an auth_scheme (:basic_auth or :request_body) to be set on the client, defaulting to :request_body to maintain backwards compatibility (@maletor, @bjeanes)
  • -
  • Handle redirect_uri according to the OAuth 2 spec, so it is passed on redirect and at the point of token exchange (@bjeanes)
  • -
  • Refactor handling of encoding of error responses (@urkle)
  • -
  • Avoid instantiating an Error if there is no error to raise (@urkle)
  • -
  • Add support for Faraday 0.10 (@rhymes)
  • -
- -

-1.2.0 - 2016-07-01

- -
    -
  • TAG: v1.2.0 -
  • -
  • Properly handle encoding of error responses (so we don’t blow up, for example, when Google’s response includes a ∞) (@Motoshi-Nishihira)
  • -
  • Make a copy of the options hash in AccessToken#from_hash to avoid accidental mutations (@Linuus)
  • -
  • Use raise rather than fail to throw exceptions (@sferik)
  • -
- -

-1.1.0 - 2016-01-30

- -
    -
  • TAG: v1.1.0 -
  • -
  • Various refactors (eliminating Hash#merge! usage in AccessToken#refresh!, use yield instead of #call, freezing mutable objects in constants, replacing constants with class variables) (@sferik)
  • -
  • Add support for Rack 2, and bump various other dependencies (@sferik)
  • -
- -

-1.0.0 - 2014-07-09

- - - -

Added

- -
    -
  • Add an implementation of the MAC token spec.
  • -
- -

Fixed

- -
    -
  • Fix Base64.strict_encode64 incompatibility with Ruby 1.8.7.
  • -
- -

-0.5.0 - 2011-07-29

- - - -

Changed

- -
    -
  • -breaking oauth_token renamed to oauth_bearer.
  • -
  • -breaking authorize_path Client option renamed to authorize_url.
  • -
  • -breaking access_token_path Client option renamed to token_url.
  • -
  • -breaking access_token_method Client option renamed to token_method.
  • -
  • -breaking web_server renamed to auth_code.
  • -
- -

-0.4.1 - 2011-04-20

- - - -

-0.4.0 - 2011-04-20

- - - -

-0.3.0 - 2011-04-08

- - - -

-0.2.0 - 2011-04-01

- - - -

-0.1.1 - 2011-01-12

- - - -

-0.1.0 - 2010-10-13

- - - -

-0.0.13 - 2010-08-17

- - - -

-0.0.12 - 2010-08-17

- - - -

-0.0.11 - 2010-08-17

- - - -

-0.0.10 - 2010-06-19

- - - -

-0.0.9 - 2010-06-18

- - - -

-0.0.8 - 2010-04-27

- - - -

-0.0.7 - 2010-04-27

- - - -

-0.0.6 - 2010-04-25

- - - -

-0.0.5 - 2010-04-23

- - - -

-0.0.4 - 2010-04-22

- - - -

-0.0.3 - 2010-04-22

- - - -

-0.0.2 - 2010-04-22

- - - -

-0.0.1 - 2010-04-22

- - - -
- - - -
- - \ No newline at end of file diff --git a/docs/file.CITATION.html b/docs/file.CITATION.html index eba7442c..e69de29b 100644 --- a/docs/file.CITATION.html +++ b/docs/file.CITATION.html @@ -1,92 +0,0 @@ - - - - - - - File: CITATION - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

cff-version: 1.2.0
-title: oauth2
-message: >-
- If you use this work and you want to cite it,
- then you can use the metadata from this file.
-type: software
-authors:

-
    -
  • given-names: Peter Hurn
    -family-names: Boling
    -email: peter@railsbling.com
    -affiliation: railsbling.com
    -orcid: ‘https://orcid.org/0009-0008-8519-441X’
    -identifiers:
  • -
  • type: url
    -value: ‘https://github.com/ruby-oauth/oauth2’
    -description: oauth2
    -repository-code: ‘https://github.com/ruby-oauth/oauth2’
    -abstract: >-
    - oauth2
    -license: See license file
  • -
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.CODE_OF_CONDUCT.html b/docs/file.CODE_OF_CONDUCT.html index cbeb7767..e69de29b 100644 --- a/docs/file.CODE_OF_CONDUCT.html +++ b/docs/file.CODE_OF_CONDUCT.html @@ -1,201 +0,0 @@ - - - - - - - File: CODE_OF_CONDUCT - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Contributor Covenant Code of Conduct

- -

Our Pledge

- -

We as members, contributors, and leaders pledge to make participation in our
-community a harassment-free experience for everyone, regardless of age, body
-size, visible or invisible disability, ethnicity, sex characteristics, gender
-identity and expression, level of experience, education, socio-economic status,
-nationality, personal appearance, race, caste, color, religion, or sexual
-identity and orientation.

- -

We pledge to act and interact in ways that contribute to an open, welcoming,
-diverse, inclusive, and healthy community.

- -

Our Standards

- -

Examples of behavior that contributes to a positive environment for our
-community include:

- -
    -
  • Demonstrating empathy and kindness toward other people
  • -
  • Being respectful of differing opinions, viewpoints, and experiences
  • -
  • Giving and gracefully accepting constructive feedback
  • -
  • Accepting responsibility and apologizing to those affected by our mistakes,
    -and learning from the experience
  • -
  • Focusing on what is best not just for us as individuals, but for the overall
    -community
  • -
- -

Examples of unacceptable behavior include:

- -
    -
  • The use of sexualized language or imagery, and sexual attention or advances of
    -any kind
  • -
  • Trolling, insulting or derogatory comments, and personal or political attacks
  • -
  • Public or private harassment
  • -
  • Publishing others’ private information, such as a physical or email address,
    -without their explicit permission
  • -
  • Other conduct which could reasonably be considered inappropriate in a
    -professional setting
  • -
- -

Enforcement Responsibilities

- -

Community leaders are responsible for clarifying and enforcing our standards of
-acceptable behavior and will take appropriate and fair corrective action in
-response to any behavior that they deem inappropriate, threatening, offensive,
-or harmful.

- -

Community leaders have the right and responsibility to remove, edit, or reject
-comments, commits, code, wiki edits, issues, and other contributions that are
-not aligned to this Code of Conduct, and will communicate reasons for moderation
-decisions when appropriate.

- -

Scope

- -

This Code of Conduct applies within all community spaces, and also applies when
-an individual is officially representing the community in public spaces.
-Examples of representing our community include using an official email address,
-posting via an official social media account, or acting as an appointed
-representative at an online or offline event.

- -

Enforcement

- -

Instances of abusive, harassing, or otherwise unacceptable behavior may be
-reported to the community leaders responsible for enforcement at
-Contact Maintainer.
-All complaints will be reviewed and investigated promptly and fairly.

- -

All community leaders are obligated to respect the privacy and security of the
-reporter of any incident.

- -

Enforcement Guidelines

- -

Community leaders will follow these Community Impact Guidelines in determining
-the consequences for any action they deem in violation of this Code of Conduct:

- -

1. Correction

- -

Community Impact: Use of inappropriate language or other behavior deemed
-unprofessional or unwelcome in the community.

- -

Consequence: A private, written warning from community leaders, providing
-clarity around the nature of the violation and an explanation of why the
-behavior was inappropriate. A public apology may be requested.

- -

2. Warning

- -

Community Impact: A violation through a single incident or series of
-actions.

- -

Consequence: A warning with consequences for continued behavior. No
-interaction with the people involved, including unsolicited interaction with
-those enforcing the Code of Conduct, for a specified period of time. This
-includes avoiding interactions in community spaces as well as external channels
-like social media. Violating these terms may lead to a temporary or permanent
-ban.

- -

3. Temporary Ban

- -

Community Impact: A serious violation of community standards, including
-sustained inappropriate behavior.

- -

Consequence: A temporary ban from any sort of interaction or public
-communication with the community for a specified period of time. No public or
-private interaction with the people involved, including unsolicited interaction
-with those enforcing the Code of Conduct, is allowed during this period.
-Violating these terms may lead to a permanent ban.

- -

4. Permanent Ban

- -

Community Impact: Demonstrating a pattern of violation of community
-standards, including sustained inappropriate behavior, harassment of an
-individual, or aggression toward or disparagement of classes of individuals.

- -

Consequence: A permanent ban from any sort of public interaction within the
-community.

- -

Attribution

- -

This Code of Conduct is adapted from the Contributor Covenant,
-version 2.1, available at
-https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.

- -

Community Impact Guidelines were inspired by
-Mozilla’s code of conduct enforcement ladder.

- -

For answers to common questions about this code of conduct, see the FAQ at
-https://www.contributor-covenant.org/faq. Translations are available at
-https://www.contributor-covenant.org/translations.

- -
- - - -
- - \ No newline at end of file diff --git a/docs/file.CONTRIBUTING.html b/docs/file.CONTRIBUTING.html index 258f8044..e69de29b 100644 --- a/docs/file.CONTRIBUTING.html +++ b/docs/file.CONTRIBUTING.html @@ -1,314 +0,0 @@ - - - - - - - File: CONTRIBUTING - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Contributing

- -

Bug reports and pull requests are welcome on CodeBerg, GitLab, or GitHub.
-This project should be a safe, welcoming space for collaboration, so contributors agree to adhere to
-the code of conduct.

- -

To submit a patch, please fork the project, create a patch with tests, and send a pull request.

- -

Remember to Keep A Changelog if you make changes.

- -

Help out!

- -

Take a look at the reek list which is the file called REEK and find something to improve.

- -

Follow these instructions:

- -
    -
  1. Fork the repository
  2. -
  3. Create a feature branch (git checkout -b my-new-feature)
  4. -
  5. Make some fixes.
  6. -
  7. Commit changes (git commit -am 'Added some feature')
  8. -
  9. Push to the branch (git push origin my-new-feature)
  10. -
  11. Make sure to add tests for it. This is important, so it doesn’t break in a future release.
  12. -
  13. Create new Pull Request.
  14. -
- -

Executables vs Rake tasks

- -

Executables shipped by dependencies, such as kettle-dev, and stone_checksums, are available
-after running bin/setup. These include:

- -
    -
  • gem_checksums
  • -
  • kettle-changelog
  • -
  • kettle-commit-msg
  • -
  • kettle-dev-setup
  • -
  • kettle-dvcs
  • -
  • kettle-pre-release
  • -
  • kettle-readme-backers
  • -
  • kettle-release
  • -
- -

There are many Rake tasks available as well. You can see them by running:

- -
bin/rake -T
-
- -

Environment Variables for Local Development

- -

Below are the primary environment variables recognized by stone_checksums (and its integrated tools). Unless otherwise noted, set boolean values to the string “true” to enable.

- -

General/runtime

-
    -
  • DEBUG: Enable extra internal logging for this library (default: false)
  • -
  • REQUIRE_BENCH: Enable require_bench to profile requires (default: false)
  • -
  • CI: When set to true, adjusts default rake tasks toward CI behavior
  • -
- -

Coverage (kettle-soup-cover / SimpleCov)

-
    -
  • K_SOUP_COV_DO: Enable coverage collection (default: true in .envrc)
  • -
  • K_SOUP_COV_FORMATTERS: Comma-separated list of formatters (html, xml, rcov, lcov, json, tty)
  • -
  • K_SOUP_COV_MIN_LINE: Minimum line coverage threshold (integer, e.g., 100)
  • -
  • K_SOUP_COV_MIN_BRANCH: Minimum branch coverage threshold (integer, e.g., 100)
  • -
  • K_SOUP_COV_MIN_HARD: Fail the run if thresholds are not met (true/false)
  • -
  • K_SOUP_COV_MULTI_FORMATTERS: Enable multiple formatters at once (true/false)
  • -
  • K_SOUP_COV_OPEN_BIN: Path to browser opener for HTML (empty disables auto-open)
  • -
  • MAX_ROWS: Limit console output rows for simplecov-console (e.g., 1)
    -Tip: When running a single spec file locally, you may want K_SOUP_COV_MIN_HARD=false to avoid failing thresholds for a partial run.
  • -
- -

GitHub API and CI helpers

-
    -
  • GITHUB_TOKEN or GH_TOKEN: Token used by ci:act and release workflow checks to query GitHub Actions status at higher rate limits
  • -
- -

Releasing and signing

-
    -
  • SKIP_GEM_SIGNING: If set, skip gem signing during build/release
  • -
  • GEM_CERT_USER: Username for selecting your public cert in certs/<USER>.pem (defaults to $USER)
  • -
  • SOURCE_DATE_EPOCH: Reproducible build timestamp. -
      -
    • -kettle-release will set this automatically for the session.
    • -
    • Not needed on bundler >= 2.7.0, as reproducible builds have become the default.
    • -
    -
  • -
- -

Git hooks and commit message helpers (exe/kettle-commit-msg)

-
    -
  • GIT_HOOK_BRANCH_VALIDATE: Branch name validation mode (e.g., jira) or false to disable
  • -
  • GIT_HOOK_FOOTER_APPEND: Append a footer to commit messages when goalie allows (true/false)
  • -
  • GIT_HOOK_FOOTER_SENTINEL: Required when footer append is enabled — a unique first-line sentinel to prevent duplicates
  • -
  • GIT_HOOK_FOOTER_APPEND_DEBUG: Extra debug output in the footer template (true/false)
  • -
- -

For a quick starting point, this repository’s .envrc shows sane defaults, and .env.local can override them locally.

- -

Appraisals

- -

From time to time the appraisal2 gemfiles in gemfiles/ will need to be updated.
-They are created and updated with the commands:

- -
bin/rake appraisal:update
-
- -

When adding an appraisal to CI, check the runner tool cache to see which runner to use.

- -

The Reek List

- -

Take a look at the reek list which is the file called REEK and find something to improve.

- -

To refresh the reek list:

- -
bundle exec reek > REEK
-
- -

Run Tests

- -

To run all tests

- -
bundle exec rake test
-
- -

Spec organization (required)

- -
    -
  • One spec file per class/module. For each class or module under lib/, keep all of its unit tests in a single spec file under spec/ that mirrors the path and file name exactly: lib/oauth2/my_class.rb -> spec/oauth2/my_class_spec.rb.
  • -
  • Exception: Integration specs that intentionally span multiple classes. Place these under spec/integration/ (or a clearly named integration folder), and do not directly mirror a single class. Name them after the scenario, not a class.
  • -
- -

Lint It

- -

Run all the default tasks, which includes running the gradually autocorrecting linter, rubocop-gradual.

- -
bundle exec rake
-
- -

Or just run the linter.

- -
bundle exec rake rubocop_gradual:autocorrect
-
- -

For more detailed information about using RuboCop in this project, please see the RUBOCOP.md guide. This project uses rubocop_gradual instead of vanilla RuboCop, which requires specific commands for checking violations.

- -

Important: Do not add inline RuboCop disables

- -

Never add # rubocop:disable ... / # rubocop:enable ... comments to code or specs (except when following the few existing rubocop:disable patterns for a rule already being disabled elsewhere in the code). Instead:

- -
    -
  • Prefer configuration-based exclusions when a rule should not apply to certain paths or files (e.g., via .rubocop.yml).
  • -
  • When a violation is temporary, and you plan to fix it later, record it in .rubocop_gradual.lock using the gradual workflow: -
      -
    • -bundle exec rake rubocop_gradual:autocorrect (preferred)
    • -
    • -bundle exec rake rubocop_gradual:force_update (only when you cannot fix the violations immediately)
    • -
    -
  • -
- -

As a general rule, fix style issues rather than ignoring them. For example, our specs should follow RSpec conventions like using described_class for the class under test.

- -

Contributors

- -

Your picture could be here!

- -

Contributors

- -

Made with contributors-img.

- -

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

- -

For Maintainers

- -

One-time, Per-maintainer, Setup

- -

IMPORTANT: To sign a build,
-a public key for signing gems will need to be picked up by the line in the
-gemspec defining the spec.cert_chain (check the relevant ENV variables there).
-All releases are signed releases.
-See: RubyGems Security Guide

- -

NOTE: To build without signing the gem set SKIP_GEM_SIGNING to any value in the environment.

- -

To release a new version:

- -

Automated process

- -
    -
  1. Update version.rb to contain the correct version-to-be-released.
  2. -
  3. Run bundle exec kettle-changelog.
  4. -
  5. Run bundle exec kettle-release.
  6. -
  7. Stay awake and monitor the release process for any errors, and answer any prompts.
  8. -
- -

Manual process

- -
    -
  1. Run bin/setup && bin/rake as a “test, coverage, & linting” sanity check
  2. -
  3. Update the version number in version.rb, and ensure CHANGELOG.md reflects changes
  4. -
  5. Run bin/setup && bin/rake again as a secondary check, and to update Gemfile.lock -
  6. -
  7. Run git commit -am "🔖 Prepare release v<VERSION>" to commit the changes
  8. -
  9. Run git push to trigger the final CI pipeline before release, and merge PRs - -
  10. -
  11. Run export GIT_TRUNK_BRANCH_NAME="$(git remote show origin | grep 'HEAD branch' | cut -d ' ' -f5)" && echo $GIT_TRUNK_BRANCH_NAME -
  12. -
  13. Run git checkout $GIT_TRUNK_BRANCH_NAME -
  14. -
  15. Run git pull origin $GIT_TRUNK_BRANCH_NAME to ensure latest trunk code
  16. -
  17. Optional for older Bundler (< 2.7.0): Set SOURCE_DATE_EPOCH so rake build and rake release use the same timestamp and generate the same checksums -
      -
    • If your Bundler is >= 2.7.0, you can skip this; builds are reproducible by default.
    • -
    • Run export SOURCE_DATE_EPOCH=$EPOCHSECONDS && echo $SOURCE_DATE_EPOCH -
    • -
    • If the echo above has no output, then it didn’t work.
    • -
    • Note: zsh/datetime module is needed, if running zsh.
    • -
    • In older versions of bash you can use date +%s instead, i.e. export SOURCE_DATE_EPOCH=$(date +%s) && echo $SOURCE_DATE_EPOCH -
    • -
    -
  18. -
  19. Run bundle exec rake build -
  20. -
  21. Run bin/gem_checksums (more context 1, 2)
    -to create SHA-256 and SHA-512 checksums. This functionality is provided by the stone_checksums
    -gem. -
      -
    • The script automatically commits but does not push the checksums
    • -
    -
  22. -
  23. Sanity check the SHA256, comparing with the output from the bin/gem_checksums command: -
      -
    • sha256sum pkg/<gem name>-<version>.gem
    • -
    -
  24. -
  25. Run bundle exec rake release which will create a git tag for the version,
    -push git commits and tags, and push the .gem file to the gem host configured in the gemspec.
  26. -
- -
- - - -
- - \ No newline at end of file diff --git a/docs/file.FUNDING.html b/docs/file.FUNDING.html index b9bcffdb..e69de29b 100644 --- a/docs/file.FUNDING.html +++ b/docs/file.FUNDING.html @@ -1,109 +0,0 @@ - - - - - - - File: FUNDING - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -
- -

Official Discord 👉️ Live Chat on Discord

- -

Many paths lead to being a sponsor or a backer of this project. Are you on such a path?

- -

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

- - - -

🤑 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

- -

Another Way to Support Open Source Software

- -

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

- -
- - - -
- - \ No newline at end of file diff --git a/docs/file.IRP.html b/docs/file.IRP.html index ee5c595c..e69de29b 100644 --- a/docs/file.IRP.html +++ b/docs/file.IRP.html @@ -1,221 +0,0 @@ - - - - - - - File: IRP - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Incident Response Plan (IRP)

- -

Status: Draft

- -

Purpose

- -

This Incident Response Plan (IRP) defines the steps the project maintainer(s) will follow when handling security incidents related to the oauth2 gem. It is written for a small project with a single primary maintainer and is intended to be practical, concise, and actionable.

- -

Scope

- -

Applies to security incidents that affect the oauth2 codebase, releases (gems), CI/CD infrastructure related to building and publishing the gem, repository credentials, or any compromise of project infrastructure that could impact users.

- -

Key assumptions

-
    -
  • This project is maintained primarily by a single maintainer.
  • -
  • Public vulnerability disclosure is handled via Tidelift (see SECURITY.md).
  • -
  • The maintainer will act as incident commander unless otherwise delegated.
  • -
- -

Contact & Roles

- -
    -
  • Incident Commander: Primary maintainer (repo owner). Responsible for coordinating triage, remediation, and communications.
  • -
  • Secondary Contact: (optional) A trusted collaborator or organization contact if available.
  • -
- -

If you are an external reporter

-
    -
  • Do not publicly disclose details of an active vulnerability before coordination via Tidelift.
  • -
  • See SECURITY.md for Tidelift disclosure instructions. If the reporter has questions and cannot use Tidelift, they may open a direct encrypted report as described in SECURITY.md (if available) or email the maintainer contact listed in the repository.
  • -
- -

Incident Handling Workflow (high level)

-
    -
  1. Identification & Reporting -
      -
    • Reports may arrive via Tidelift, issue tracker, direct email, or third-party advisories.
    • -
    • Immediately acknowledge receipt (within 24-72 hours) via the reporting channel.
    • -
    -
  2. -
  3. Triage & Initial Assessment (first 72 hours) -
      -
    • Confirm the report is not duplicative and gather: reproducer, affected versions, attack surface, exploitability, and CVSS-like severity estimate.
    • -
    • Verify the issue against the codebase and reproduce locally if possible.
    • -
    • Determine scope: which versions are affected, whether the issue is in code paths executed in common setups, and whether a workaround exists.
    • -
    -
  4. -
  5. Containment & Mitigation -
      -
    • If a simple mitigation or workaround (configuration change, safe default, or recommended upgrade) exists, document it clearly in the issue/Tidelift advisory.
    • -
    • If immediate removal of a release is required (rare), consult Tidelift for coordinated takedown and notify package hosts if applicable.
    • -
    -
  6. -
  7. Remediation & Patch -
      -
    • Prepare a fix in a branch with tests and changelog entries. Prefer minimal, well-tested changes.
    • -
    • Include tests that reproduce the faulty behavior and demonstrate the fix.
    • -
    • Hardening: add fuzz tests, input validation, or additional checks as appropriate.
    • -
    -
  8. -
  9. Release & Disclosure -
      -
    • Coordinate disclosure through Tidelift per SECURITY.md timelines. Aim for a coordinated disclosure and patch release to minimize risk to users.
    • -
    • Publish a patch release (increment gem version) and an advisory via Tidelift.
    • -
    • Update CHANGELOG.md and repository release notes with non-sensitive details.
    • -
    -
  10. -
  11. Post-Incident -
      -
    • Produce a short postmortem: timeline, root cause, actions taken, and follow-ups.
    • -
    • Add/adjust tests and CI checks to prevent regressions.
    • -
    • If credentials or infrastructure were compromised, rotate secrets and audit access.
    • -
    -
  12. -
- -

Severity classification (guidance)

-
    -
  • High/Critical: Remote code execution, data exfiltration, or any vulnerability that can be exploited without user interaction. Immediate action and prioritized patching.
  • -
  • Medium: Privilege escalation, sensitive information leaks that require specific conditions. Patch in the next release cycle with advisory.
  • -
  • Low: Minor information leaks, UI issues, or non-exploitable bugs. Fix normally and include in the next scheduled release.
  • -
- -

Preservation of evidence

-
    -
  • Preserve all reporter-provided data, logs, and reproducer code in a secure location (local encrypted storage or private branch) for the investigation.
  • -
  • Do not publish evidence that would enable exploitation before coordinated disclosure.
  • -
- -

Communication templates

-

Acknowledgement (to reporter)

- -

“Thank you for reporting this issue. I’ve received your report and will triage it within 72 hours. If you can, please provide reproduction steps, affected versions, and any exploit PoC. I will coordinate disclosure through Tidelift per the project’s security policy.”

- -

Public advisory (after patch is ready)

- -

“A security advisory for oauth2 (versions X.Y.Z) has been published via Tidelift. Please upgrade to version A.B.C which patches [brief description]. See the advisory for details and recommended mitigations.”

- -

Runbook: Quick steps for a maintainer to patch and release

-
    -
  1. Create a branch: git checkout -b fix/security-brief-description -
  2. -
  3. Reproduce the issue locally and add a regression spec in spec/.
  4. -
  5. Implement the fix and run the test suite: bundle exec rspec (or the project’s preferred test command).
  6. -
  7. Bump version in lib/oauth2/version.rb following semantic versioning.
  8. -
  9. Update CHANGELOG.md with an entry describing the fix (avoid exploit details).
  10. -
  11. Commit and push the branch, open a PR, and merge after approvals.
  12. -
  13. Build and push the gem: gem build oauth2.gemspec && gem push pkg/... (coordinate with Tidelift before public push if disclosure is coordinated).
  14. -
  15. Publish a release on GitHub and ensure the Tidelift advisory is posted.
  16. -
- -

Operational notes

-
    -
  • Secrets: Use local encrypted storage for any sensitive reporter data. If repository or CI secrets may be compromised, rotate them immediately and update dependent services.
  • -
  • Access control: Limit who can publish gems and who has admin access to the repo. Keep an up-to-date list of collaborators in a secure place.
  • -
- - -
    -
  • If the incident involves user data or has legal implications, consult legal counsel or the maintainers’ employer as appropriate. The maintainer should document the timeline and all communications.
  • -
- -

Retrospective & continuous improvement

-

After an incident, perform a brief post-incident review covering:

-
    -
  • What happened and why
  • -
  • What was done to contain and remediate
  • -
  • What tests or process changes will prevent recurrence
  • -
  • Assign owners and deadlines for follow-up tasks
  • -
- -

References

-
    -
  • See SECURITY.md for the project’s official disclosure channel (Tidelift).
  • -
- -

Appendix: Example checklist for an incident

-
    -
  • -Acknowledge report to reporter (24-72 hours)
  • -
  • -Reproduce and classify severity
  • -
  • -Prepare and test a fix in a branch
  • -
  • -Coordinate disclosure via Tidelift
  • -
  • -Publish patch release and advisory
  • -
  • -Postmortem and follow-up actions
  • -
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.LICENSE.html b/docs/file.LICENSE.html index 590a43a5..e69de29b 100644 --- a/docs/file.LICENSE.html +++ b/docs/file.LICENSE.html @@ -1,70 +0,0 @@ - - - - - - - File: LICENSE - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -
MIT License

Copyright (c) 2017-2026 Peter H. Boling, of Galtzo.com, and oauth2 contributors
Copyright (c) 2011-2013 Michael Bleigh and Intridea, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- - - -
- - \ No newline at end of file diff --git a/docs/file.OIDC.html b/docs/file.OIDC.html index c61ee552..e69de29b 100644 --- a/docs/file.OIDC.html +++ b/docs/file.OIDC.html @@ -1,266 +0,0 @@ - - - - - - - File: OIDC - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

OpenID Connect (OIDC) with ruby-oauth/oauth2

- -

OIDC Libraries

- -

Libraries built on top of the oauth2 gem that implement OIDC.

- - - -

If any other libraries would like to be added to this list, please open an issue or pull request.

- -

Raw OIDC with ruby-oauth/oauth2

- -

This document complements the inline documentation by focusing on OpenID Connect (OIDC) 1.0 usage patterns when using this gem as an OAuth 2.0 client library.

- -

Scope of this document

- -
    -
  • Audience: Developers building an OAuth 2.0/OIDC Relying Party (RP, aka client) in Ruby.
  • -
  • Non-goals: This gem does not implement an OIDC Provider (OP, aka Authorization Server); for OP/server see other projects (e.g., doorkeeper + oidc extensions).
  • -
  • Status: Informational documentation with links to normative specs. The gem intentionally remains protocol-agnostic beyond OAuth 2.0; OIDC specifics (like ID Token validation) must be handled by your application.
  • -
- -

Key concepts refresher

- -
    -
  • OAuth 2.0 delegates authorization; it does not define authentication of the end-user.
  • -
  • OIDC layers an identity layer on top of OAuth 2.0, introducing: -
      -
    • ID Token: a JWT carrying claims about the authenticated end-user and the authentication event.
    • -
    • Standardized scopes: openid (mandatory), profile, email, address, phone, offline_access, and others.
    • -
    • UserInfo endpoint: a protected resource for retrieving user profile claims.
    • -
    • Discovery and Dynamic Client Registration (optional for providers/clients that support them).
    • -
    -
  • -
- -

What this gem provides for OIDC

- -
    -
  • All OAuth 2.0 client capabilities required for OIDC flows: building authorization requests, exchanging authorization codes, refreshing tokens, and making authenticated resource requests.
  • -
  • Transport and parsing conveniences (snaky hash, Faraday integration, error handling, etc.).
  • -
  • Optional client authentication schemes useful with OIDC deployments: -
      -
    • basic_auth (default)
    • -
    • request_body (legacy)
    • -
    • tls_client_auth (MTLS)
    • -
    • private_key_jwt (OIDC-compliant when configured per OP requirements)
    • -
    -
  • -
- -

What you must add in your app for OIDC

- -
    -
  • ID Token validation: This gem surfaces id_token values but does not verify them. Your app should:
    -1) Parse the JWT (header, payload, signature)
    -2) Fetch the OP JSON Web Key Set (JWKS) from discovery (or configure statically)
    -3) Select the correct key by kid (when present) and verify the signature and algorithm
    -4) Validate standard claims (iss, aud, exp, iat, nbf, azp, nonce when used, at_hash/c_hash when applicable)
    -5) Enforce expected client_id, issuer, and clock skew policies
  • -
  • Nonce handling for Authorization Code flow with OIDC: generate a cryptographically-random nonce, bind it to the user session before redirect, include it in authorize request, and verify it in the ID Token on return.
  • -
  • PKCE is best practice and often required by OPs: generate/verifier, send challenge in authorize, send verifier in token request.
  • -
  • Session/state management: continue to validate state to mitigate CSRF; use exact redirect_uri matching.
  • -
- -

Minimal OIDC Authorization Code example

- -
require "oauth2"
-require "jwt"         # jwt/ruby-jwt
-require "net/http"
-require "json"
-
-client = OAuth2::Client.new(
-  ENV.fetch("OIDC_CLIENT_ID"),
-  ENV.fetch("OIDC_CLIENT_SECRET"),
-  site: ENV.fetch("OIDC_ISSUER"),              # e.g. https://accounts.example.com
-  authorize_url: "/authorize",                 # or discovered
-  token_url: "/token",                         # or discovered
-)
-
-# Step 1: Redirect to OP for consent/auth
-state = SecureRandom.hex(16)
-nonce = SecureRandom.hex(16)
-pkce_verifier = SecureRandom.urlsafe_base64(64)
-pkce_challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(pkce_verifier)).delete("=")
-
-authz_url = client.auth_code.authorize_url(
-  scope: "openid profile email",
-  state: state,
-  nonce: nonce,
-  code_challenge: pkce_challenge,
-  code_challenge_method: "S256",
-  redirect_uri: ENV.fetch("OIDC_REDIRECT_URI"),
-)
-# redirect_to authz_url
-
-# Step 2: Handle callback
-# params[:code], params[:state]
-raise "state mismatch" unless params[:state] == state
-
-token = client.auth_code.get_token(
-  params[:code],
-  redirect_uri: ENV.fetch("OIDC_REDIRECT_URI"),
-  code_verifier: pkce_verifier,
-)
-
-# The token may include: access_token, id_token, refresh_token, etc.
-id_token = token.params["id_token"] || token.params[:id_token]
-
-# Step 3: Validate the ID Token (simplified – add your own checks!)
-# Discover keys (example using .well-known)
-issuer = ENV.fetch("OIDC_ISSUER")
-jwks_uri = JSON.parse(Net::HTTP.get(URI.join(issuer, "/.well-known/openid-configuration"))).
-  fetch("jwks_uri")
-jwks = JSON.parse(Net::HTTP.get(URI(jwks_uri)))
-keys = jwks.fetch("keys")
-
-# Use ruby-jwt JWK loader
-jwk_set = JWT::JWK::Set.new(keys.map { |k| JWT::JWK.import(k) })
-
-decoded, headers = JWT.decode(
-  id_token,
-  nil,
-  true,
-  algorithms: ["RS256", "ES256", "PS256"],
-  jwks: jwk_set,
-  verify_iss: true,
-  iss: issuer,
-  verify_aud: true,
-  aud: ENV.fetch("OIDC_CLIENT_ID"),
-)
-
-# Verify nonce
-raise "nonce mismatch" unless decoded["nonce"] == nonce
-
-# Optionally: call UserInfo
-userinfo = token.get("/userinfo").parsed
-
- -

Notes on discovery and registration

- -
    -
  • Discovery: Most OPs publish configuration at {issuer}/.well-known/openid-configuration (OIDC Discovery 1.0). From there, resolve authorization_endpoint, token_endpoint, jwks_uri, userinfo_endpoint, etc.
  • -
  • Dynamic Client Registration: Some OPs allow registering clients programmatically (OIDC Dynamic Client Registration 1.0). This gem does not implement registration; use a plain HTTP client or Faraday and store credentials securely.
  • -
- -

Common pitfalls and tips

- -
    -
  • Always request the openid scope when you expect an ID Token. Without it, the OP may behave as vanilla OAuth 2.0.
  • -
  • Validate ID Token signature and claims before trusting any identity data. Do not rely solely on the presence of an id_token field.
  • -
  • Prefer Authorization Code + PKCE. Avoid Implicit; it is discouraged in modern guidance and may be disabled by providers.
  • -
  • Use exact redirect_uri matching, and keep your allow-list short.
  • -
  • For public clients that use refresh tokens, prefer sender-constrained tokens (DPoP/MTLS) or rotation with one-time-use refresh tokens, per modern best practices.
  • -
  • When using private_key_jwt, ensure the “aud” (or token_url) and “iss/sub” claims are set per the OP’s rules, and include kid in the JWT header when required so the OP can select the right key.
  • -
- -

Relevant specifications and references

- -
    -
  • OpenID Connect Core 1.0: https://openid.net/specs/openid-connect-core-1_0.html
  • -
  • OIDC Core (final): https://openid.net/specs/openid-connect-core-1_0-final.html
  • -
  • How OIDC works: https://openid.net/developers/how-connect-works/
  • -
  • OpenID Connect home: https://openid.net/connect/
  • -
  • OIDC Discovery 1.0: https://openid.net/specs/openid-connect-discovery-1_0.html
  • -
  • OIDC Dynamic Client Registration 1.0: https://openid.net/specs/openid-connect-registration-1_0.html
  • -
  • OIDC Session Management 1.0: https://openid.net/specs/openid-connect-session-1_0.html
  • -
  • OIDC RP-Initiated Logout 1.0: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
  • -
  • OIDC Back-Channel Logout 1.0: https://openid.net/specs/openid-connect-backchannel-1_0.html
  • -
  • OIDC Front-Channel Logout 1.0: https://openid.net/specs/openid-connect-frontchannel-1_0.html
  • -
  • Auth0 OIDC overview: https://auth0.com/docs/authenticate/protocols/openid-connect-protocol
  • -
  • Spring Authorization Server’s list of OAuth2/OIDC specs: https://github.com/spring-projects/spring-authorization-server/wiki/OAuth2-and-OIDC-Specifications
  • -
- -

See also

- -
    -
  • README sections on OAuth 2.1 notes and OIDC notes
  • -
  • Strategy classes under lib/oauth2/strategy for flow helpers
  • -
  • Specs under spec/oauth2 for concrete usage patterns
  • -
- -

Contributions welcome

- -
    -
  • If you discover provider-specific nuances, consider contributing examples or clarifications (without embedding provider-specific hacks into the library).
  • -
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.README.html b/docs/file.README.html index bec62448..e69de29b 100644 --- a/docs/file.README.html +++ b/docs/file.README.html @@ -1,1655 +0,0 @@ - - - - - - - File: README - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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 Open Source Helpers 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
-
- -

🔧 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.

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

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 - - - - - -
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.REEK.html b/docs/file.REEK.html index 967ab7e7..e69de29b 100644 --- a/docs/file.REEK.html +++ b/docs/file.REEK.html @@ -1,71 +0,0 @@ - - - - - - - File: REEK - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.RUBOCOP.html b/docs/file.RUBOCOP.html index 72d256e2..e69de29b 100644 --- a/docs/file.RUBOCOP.html +++ b/docs/file.RUBOCOP.html @@ -1,171 +0,0 @@ - - - - - - - File: RUBOCOP - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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
  • -
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.SECURITY.html b/docs/file.SECURITY.html index aa31edb4..e69de29b 100644 --- a/docs/file.SECURITY.html +++ b/docs/file.SECURITY.html @@ -1,103 +0,0 @@ - - - - - - - File: SECURITY - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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.

- -
- - - -
- - \ No newline at end of file diff --git a/docs/file.THREAT_MODEL.html b/docs/file.THREAT_MODEL.html index dc3ccd32..e69de29b 100644 --- a/docs/file.THREAT_MODEL.html +++ b/docs/file.THREAT_MODEL.html @@ -1,216 +0,0 @@ - - - - - - - File: THREAT_MODEL - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Threat Model Outline for oauth2 Ruby Gem

- -

1. Overview

-

This document outlines the threat model for the oauth2 Ruby gem, which implements OAuth 2.0, 2.1, and OIDC Core protocols. The gem is used to facilitate secure authorization and authentication in Ruby applications.

- -

2. Assets to Protect

-
    -
  • OAuth access tokens, refresh tokens, and ID tokens
  • -
  • User credentials (if handled)
  • -
  • Client secrets and application credentials
  • -
  • Sensitive user data accessed via OAuth
  • -
  • Private keys and certificates (for signing/verifying tokens)
  • -
- -

3. Potential Threat Actors

-
    -
  • External attackers (internet-based)
  • -
  • Malicious OAuth clients or resource servers
  • -
  • Insiders (developers, maintainers)
  • -
  • Compromised dependencies
  • -
- -

4. Attack Surfaces

-
    -
  • OAuth endpoints (authorization, token, revocation, introspection)
  • -
  • HTTP request/response handling
  • -
  • Token storage and management
  • -
  • Configuration files and environment variables
  • -
  • Dependency supply chain
  • -
- -

5. Threats and Mitigations

- -

5.1 Token Leakage

-
    -
  • -Threat: Tokens exposed via logs, URLs, or insecure storage
  • -
  • -Mitigations: -
      -
    • Avoid logging sensitive tokens
    • -
    • Use secure storage mechanisms
    • -
    • Never expose tokens in URLs
    • -
    -
  • -
- -

5.2 Token Replay and Forgery

-
    -
  • -Threat: Attackers reuse or forge tokens
  • -
  • -Mitigations: -
      -
    • Validate token signatures and claims
    • -
    • Use short-lived tokens and refresh tokens
    • -
    • Implement token revocation
    • -
    -
  • -
- -

5.3 Insecure Communication

-
    -
  • -Threat: Data intercepted via MITM attacks
  • -
  • -Mitigations: -
      -
    • Enforce HTTPS for all communications
    • -
    • Validate SSL/TLS certificates
    • -
    -
  • -
- -

5.4 Client Secret Exposure

-
    -
  • -Threat: Client secrets leaked in code or version control
  • -
  • -Mitigations: -
      -
    • Store secrets in environment variables or secure vaults
    • -
    • Never commit secrets to source control
    • -
    -
  • -
- -

5.5 Dependency Vulnerabilities

-
    -
  • -Threat: Vulnerabilities in third-party libraries
  • -
  • -Mitigations: -
      -
    • Regularly update dependencies
    • -
    • Use tools like bundler-audit for vulnerability scanning
    • -
    -
  • -
- -

5.6 Improper Input Validation

-
    -
  • -Threat: Injection attacks via untrusted input
  • -
  • -Mitigations: -
      -
    • Validate and sanitize all inputs
    • -
    • Use parameterized queries and safe APIs
    • -
    -
  • -
- -

5.7 Insufficient Logging and Monitoring

-
    -
  • -Threat: Attacks go undetected
  • -
  • -Mitigations: -
      -
    • Log security-relevant events (without sensitive data)
    • -
    • Monitor for suspicious activity
    • -
    -
  • -
- -

6. Assumptions

-
    -
  • The gem is used in a secure environment with up-to-date Ruby and dependencies
  • -
  • End-users are responsible for secure configuration and deployment
  • -
- -

7. Out of Scope

-
    -
  • Security of external OAuth providers
  • -
  • Application-level business logic
  • -
- -

8. References

- - -
-

This outline should be reviewed and updated regularly as the project evolves.

-
- - - -
- - \ No newline at end of file diff --git a/docs/file.access_token.html b/docs/file.access_token.html index 98b3421e..e69de29b 100644 --- a/docs/file.access_token.html +++ b/docs/file.access_token.html @@ -1,94 +0,0 @@ - - - - - - - File: access_token - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

module OAuth2
- class AccessToken
- def self.from_hash: (OAuth2::Client, Hash[untyped, untyped]) -> OAuth2::AccessToken
- def self.from_kvform: (OAuth2::Client, String) -> OAuth2::AccessToken

- -
def initialize: (OAuth2::Client, String, ?Hash[Symbol, untyped]) -> void
-def []: (String | Symbol) -> untyped
-def expires?: () -> bool
-def expired?: () -> bool
-def refresh: (?Hash[untyped, untyped], ?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::AccessToken
-def revoke: (?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::Response
-def to_hash: () -> Hash[Symbol, untyped]
-def request: (Symbol, String, ?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::Response
-def get: (String, ?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::Response
-def post: (String, ?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::Response
-def put: (String, ?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::Response
-def patch: (String, ?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::Response
-def delete: (String, ?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::Response
-def headers: () -> Hash[String, String]
-def configure_authentication!: (Hash[Symbol, untyped], Symbol) -> void
-def convert_expires_at: (untyped) -> (Time | Integer | nil)
-
-attr_accessor response: OAuth2::Response   end end
-
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.authenticator.html b/docs/file.authenticator.html index ba4a93ad..e69de29b 100644 --- a/docs/file.authenticator.html +++ b/docs/file.authenticator.html @@ -1,91 +0,0 @@ - - - - - - - File: authenticator - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

module OAuth2
- class Authenticator
- include OAuth2::FilteredAttributes

- -
attr_reader mode: (Symbol | String)
-attr_reader id: String?
-attr_reader secret: String?
-
-def initialize: (String? id, String? secret, (Symbol | String) mode) -> void
-
-def apply: (Hash[untyped, untyped]) -> Hash[untyped, untyped]
-
-def self.encode_basic_auth: (String, String) -> String
-
-private
-
-def apply_params_auth: (Hash[untyped, untyped]) -> Hash[untyped, untyped]
-def apply_client_id: (Hash[untyped, untyped]) -> Hash[untyped, untyped]
-def apply_basic_auth: (Hash[untyped, untyped]) -> Hash[untyped, untyped]
-def basic_auth_header: () -> Hash[String, String]   end end
-
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.client.html b/docs/file.client.html index 19755b28..e69de29b 100644 --- a/docs/file.client.html +++ b/docs/file.client.html @@ -1,121 +0,0 @@ - - - - - - - File: client - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

module OAuth2
- class Client
- RESERVED_REQ_KEYS: Array[String]
- RESERVED_PARAM_KEYS: Array[String]

- -
include OAuth2::FilteredAttributes
-
-attr_reader id: String
-attr_reader secret: String
-attr_reader site: String?
-attr_accessor options: Hash[Symbol, untyped]
-attr_writer connection: untyped
-
-def initialize: (String client_id, String client_secret, ?Hash[Symbol, untyped]) { (untyped) -> void } -> void
-
-def site=: (String) -> String
-
-def connection: () -> untyped
-
-def authorize_url: (?Hash[untyped, untyped]) -> String
-def token_url: (?Hash[untyped, untyped]) -> String
-def revoke_url: (?Hash[untyped, untyped]) -> String
-
-def request: (Symbol verb, String url, ?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::Response
-
-def get_token: (Hash[untyped, untyped] params, ?Hash[Symbol, untyped] access_token_opts, ?Proc) { (Hash[Symbol, untyped]) -> void } -> (OAuth2::AccessToken | nil)
-
-def revoke_token: (String token, ?String token_type_hint, ?Hash[Symbol, untyped]) { (untyped) -> void } -> OAuth2::Response
-
-def http_method: () -> Symbol
-
-def auth_code: () -> OAuth2::Strategy::AuthCode
-def implicit: () -> OAuth2::Strategy::Implicit
-def password: () -> OAuth2::Strategy::Password
-def client_credentials: () -> OAuth2::Strategy::ClientCredentials
-def assertion: () -> OAuth2::Strategy::Assertion
-
-def redirection_params: () -> Hash[String, String]
-
-private
-
-def params_to_req_opts: (Hash[untyped, untyped]) -> Hash[Symbol, untyped]
-def parse_snaky_params_headers: (Hash[untyped, untyped]) -> [Symbol, bool, untyped, (Symbol | nil), Hash[untyped, untyped], Hash[String, String]]
-def execute_request: (Symbol verb, String url, ?Hash[Symbol, untyped]) { (Faraday::Request) -> void } -> OAuth2::Response
-def authenticator: () -> OAuth2::Authenticator
-def parse_response_legacy: (OAuth2::Response, Hash[Symbol, untyped], Proc) -> (OAuth2::AccessToken | nil)
-def parse_response: (OAuth2::Response, Hash[Symbol, untyped]) -> (OAuth2::AccessToken | nil)
-def build_access_token: (OAuth2::Response, Hash[Symbol, untyped], untyped) -> OAuth2::AccessToken
-def build_access_token_legacy: (OAuth2::Response, Hash[Symbol, untyped], Proc) -> (OAuth2::AccessToken | nil)
-def oauth_debug_logging: (untyped) -> void   end end
-
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.error.html b/docs/file.error.html index 116b662b..e69de29b 100644 --- a/docs/file.error.html +++ b/docs/file.error.html @@ -1,78 +0,0 @@ - - - - - - - File: error - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

module OAuth2
- class Error < StandardError
- def initialize: (OAuth2::Response) -> void
- def code: () -> (String | Integer | nil)
- def description: () -> (String | nil)
- def response: () -> OAuth2::Response
- end
-end

-
- - - -
- - \ No newline at end of file diff --git a/docs/file.filtered_attributes.html b/docs/file.filtered_attributes.html index 174cc722..e69de29b 100644 --- a/docs/file.filtered_attributes.html +++ b/docs/file.filtered_attributes.html @@ -1,76 +0,0 @@ - - - - - - - File: filtered_attributes - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

module OAuth2
- module FilteredAttributes
- def self.included: (untyped) -> untyped
- def filtered_attributes: (*String) -> void
- end
-end

-
- - - -
- - \ No newline at end of file diff --git a/docs/file.oauth2.html b/docs/file.oauth2.html index 5e134511..e69de29b 100644 --- a/docs/file.oauth2.html +++ b/docs/file.oauth2.html @@ -1,79 +0,0 @@ - - - - - - - File: oauth2 - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

module OAuth2
- OAUTH_DEBUG: bool

- -

DEFAULT_CONFIG: untyped
- @config: untyped

- -

def self.config: () -> untyped
- def self.configure: () { (untyped) -> void } -> void
-end

-
- - - -
- - \ No newline at end of file diff --git a/docs/file.response.html b/docs/file.response.html index 397e64f3..e69de29b 100644 --- a/docs/file.response.html +++ b/docs/file.response.html @@ -1,87 +0,0 @@ - - - - - - - File: response - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

module OAuth2
- class Response
- DEFAULT_OPTIONS: Hash[Symbol, untyped]

- -
def self.register_parser: (Symbol key, (Array[String] | String) mime_types) { (String) -> untyped } -> void
-
-def initialize: (untyped response, parse: Symbol?, snaky: bool?, snaky_hash_klass: untyped?, options: Hash[Symbol, untyped]?) -> void
-def headers: () -> Hash[untyped, untyped]
-def status: () -> Integer
-def body: () -> String
-def parsed: () -> untyped
-def content_type: () -> (String | nil)
-def parser: () -> (untyped | nil)
-
-attr_reader response: untyped
-attr_accessor options: Hash[Symbol, untyped]   end end
-
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.strategy.html b/docs/file.strategy.html index 9da9d508..e69de29b 100644 --- a/docs/file.strategy.html +++ b/docs/file.strategy.html @@ -1,103 +0,0 @@ - - - - - - - File: strategy - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

module OAuth2
- module Strategy
- class Base
- def initialize: (OAuth2::Client) -> void
- end

- -
class AuthCode < Base
-  def authorize_params: (?Hash[untyped, untyped]) -> Hash[untyped, untyped]
-  def authorize_url: (?Hash[untyped, untyped]) -> String
-  def get_token: (String, ?Hash[untyped, untyped], ?Hash[Symbol, untyped]) -> OAuth2::AccessToken
-end
-
-class Implicit < Base
-  def authorize_params: (?Hash[untyped, untyped]) -> Hash[untyped, untyped]
-  def authorize_url: (?Hash[untyped, untyped]) -> String
-  def get_token: (*untyped) -> void
-end
-
-class Password < Base
-  def authorize_url: () -> void
-  def get_token: (String, String, ?Hash[untyped, untyped], ?Hash[Symbol, untyped]) -> OAuth2::AccessToken
-end
-
-class ClientCredentials < Base
-  def authorize_url: () -> void
-  def get_token: (?Hash[untyped, untyped], ?Hash[Symbol, untyped]) -> OAuth2::AccessToken
-end
-
-class Assertion < Base
-  def authorize_url: () -> void
-  def get_token: (Hash[untyped, untyped], Hash[Symbol, untyped], ?Hash[Symbol, untyped], ?Hash[Symbol, untyped]) -> OAuth2::AccessToken
-end   end end
-
-
- - - -
- - \ No newline at end of file diff --git a/docs/file.version.html b/docs/file.version.html index 1d2c0ebd..e69de29b 100644 --- a/docs/file.version.html +++ b/docs/file.version.html @@ -1,75 +0,0 @@ - - - - - - - File: version - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

module OAuth2
- module Version
- VERSION: String
- end
-end

-
- - - -
- - \ No newline at end of file diff --git a/docs/file_list.html b/docs/file_list.html index 4cc99e2f..e69de29b 100644 --- a/docs/file_list.html +++ b/docs/file_list.html @@ -1,164 +0,0 @@ - - - - - - - - - - - - - - - - - - File List - - - -
-
-

File List

- - - -
- - -
- - diff --git a/docs/frames.html b/docs/frames.html index 2febcdb5..e69de29b 100644 --- a/docs/frames.html +++ b/docs/frames.html @@ -1,22 +0,0 @@ - - - - - Documentation by YARD 0.9.38 - - - - diff --git a/docs/index.html b/docs/index.html index 78d42d62..e69de29b 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,1655 +0,0 @@ - - - - - - - File: README - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

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 Open Source Helpers 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
-
- -

🔧 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.

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

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 - - - - - -
-
- - - -
- - \ No newline at end of file diff --git a/docs/method_list.html b/docs/method_list.html index dd8fb87a..e69de29b 100644 --- a/docs/method_list.html +++ b/docs/method_list.html @@ -1,742 +0,0 @@ - - - - - - - - - - - - - - - - - - Method List - - - -
-
-

Method List

- - - -
- - -
- - diff --git a/docs/top-level-namespace.html b/docs/top-level-namespace.html index 12fca9d6..e69de29b 100644 --- a/docs/top-level-namespace.html +++ b/docs/top-level-namespace.html @@ -1,110 +0,0 @@ - - - - - - - Top Level Namespace - - — Documentation by YARD 0.9.38 - - - - - - - - - - - - - - - - - - - -
- - -

Top Level Namespace - - - -

-
- - - - - - - - - - - -
- -

Defined Under Namespace

-

- - - Modules: OAuth2 - - - - -

- - - - - - - - - -
- - - -
- - \ No newline at end of file diff --git a/lib/oauth2.rb b/lib/oauth2.rb index db9e94da..b89f72a5 100644 --- a/lib/oauth2.rb +++ b/lib/oauth2.rb @@ -10,7 +10,9 @@ # includes gem files require_relative "oauth2/version" +require_relative "oauth2/thing_filter" require_relative "oauth2/filtered_attributes" +require_relative "oauth2/sanitized_logger" require_relative "oauth2/error" require_relative "oauth2/authenticator" require_relative "oauth2/client" @@ -43,18 +45,40 @@ module OAuth2 # config[:silence_no_tokens_warning] = false # end # + # @example Customize filtered output markers and debug-log value filtering by key name + # OAuth2.configure do |config| + # config[:filtered_label] = "[REDACTED]" + # config[:filtered_debug_keys] += ["client_assertion"] + # end + # + # Existing objects and logger wrappers snapshot filtering configuration during + # initialization. Changing these config values later affects only newly + # initialized objects and debug loggers. + # # @return [SnakyHash::SymbolKeyed] A mutable Hash-like config with symbol keys DEFAULT_CONFIG = SnakyHash::SymbolKeyed.new( silence_extra_tokens_warning: true, silence_no_tokens_warning: true, + filtered_label: "[FILTERED]", + filtered_debug_keys: %w[ + access_token + refresh_token + id_token + client_secret + assertion + code_verifier + token + ], ) # The current runtime configuration for the library. # # @return [SnakyHash::SymbolKeyed] + CONFIG = DEFAULT_CONFIG.dup + class << self def config - @config ||= DEFAULT_CONFIG.dup + CONFIG end # Configure global library behavior. diff --git a/lib/oauth2/client.rb b/lib/oauth2/client.rb index 7c64c3c1..848524f2 100644 --- a/lib/oauth2/client.rb +++ b/lib/oauth2/client.rb @@ -42,7 +42,7 @@ class Client # rubocop:disable Metrics/ClassLength # @option options [Hash] :connection_opts ({}) Hash of connection options to pass to initialize Faraday # @option options [Boolean] :raise_errors (true) whether to raise an OAuth2::Error on responses with 400+ status codes # @option options [Integer] :max_redirects (5) maximum number of redirects to follow - # @option options [Logger] :logger (::Logger.new($stdout)) Logger instance for HTTP request/response output; requires OAUTH_DEBUG to be true + # @option options [Logger] :logger (::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 a {ThingFilter} initialized from `OAuth2.config[:filtered_label]` and the key names in `OAuth2.config[:filtered_debug_keys]`. # @option options [Class] :access_token_class (AccessToken) class to use for access tokens; you can subclass OAuth2::AccessToken, @version 2.0+ # @option options [Hash] :ssl SSL options for Faraday # @@ -563,7 +563,7 @@ def build_access_token_legacy(response, access_token_opts, extract_access_token) end def oauth_debug_logging(builder) - builder.response(:logger, options[:logger], bodies: true) if OAuth2::OAUTH_DEBUG + builder.response(:logger, SanitizedLogger.new(options[:logger]), bodies: true) if OAuth2::OAUTH_DEBUG end end end diff --git a/lib/oauth2/error.rb b/lib/oauth2/error.rb index bccbe193..550d4727 100644 --- a/lib/oauth2/error.rb +++ b/lib/oauth2/error.rb @@ -17,6 +17,8 @@ class Error < StandardError # @param [OAuth2::Response, Hash, Object] response A Response or error payload def initialize(response) @response = response + @code = nil + @description = nil if response.respond_to?(:parsed) if response.parsed.is_a?(Hash) @code = response.parsed["error"] diff --git a/lib/oauth2/filtered_attributes.rb b/lib/oauth2/filtered_attributes.rb index 71204621..dfee909f 100644 --- a/lib/oauth2/filtered_attributes.rb +++ b/lib/oauth2/filtered_attributes.rb @@ -1,17 +1,40 @@ +# frozen_string_literal: true + module OAuth2 - # Mixin that redacts sensitive instance variables in #inspect output. + # Mixin that redacts sensitive instance variables in `#inspect` output. + # + # Classes include this module and declare which attribute names should be + # filtered via {.filtered_attributes}. Matching and replacement behavior is + # delegated to {ThingFilter}, which is initialized once per object. # - # Classes include this module and declare which attributes should be filtered - # using {.filtered_attributes}. Any instance variable name that includes one of - # those attribute names will be shown as [FILTERED] in the object's inspect. + # This means existing objects keep the filter configuration that was present + # when they were initialized, even if global config or class-level filter + # declarations change later. module FilteredAttributes - # Hook invoked when the module is included. Extends the including class with - # class-level helpers. + class << self + # Hook invoked when the module is included. Extends the including class with + # class-level helpers and prepends the initializer hook. + # + # @param [Class] base The including class + # @return [void] + def included(base) + base.extend(ClassMethods) + base.prepend(InitializerMethods) + end + end + + # Initializer hook that snapshots the thing filter for this object. # - # @param [Class] base The including class - # @return [void] - def self.included(base) - base.extend(ClassMethods) + # The snapshot captures both the class-level filtered attribute names and + # the current `OAuth2.config[:filtered_label]` value. + module InitializerMethods + def initialize(*args, &block) + super(*args, &block) + @thing_filter = ThingFilter.new( + self.class.filtered_attribute_names, + label: OAuth2.config[:filtered_label], + ) + end end # Class-level helpers for configuring filtered attributes. @@ -30,6 +53,8 @@ def filtered_attributes(base, *attributes) # @param [Class] base The class to get filtered attributes for # @return [Array] def filtered_attribute_names(base) + return [] unless base.instance_variable_defined?(:@filtered_attribute_names) + base.instance_variable_get(:@filtered_attribute_names) || [] end end @@ -50,16 +75,24 @@ def filtered_attribute_names end end + # The initialized thing filter used by this object. + # + # This is a per-instance snapshot created during initialization. + # + # @return [ThingFilter] + def thing_filter + @thing_filter + end + # Custom inspect that redacts configured attributes. # # @return [String] def inspect - filtered_attribute_names = ClassMethods.filtered_attribute_names(self.class) - return super if filtered_attribute_names.empty? + return super if thing_filter.things.empty? inspected_vars = instance_variables.map do |var| - if filtered_attribute_names.any? { |filtered_var| var.to_s.include?(filtered_var.to_s) } - "#{var}=[FILTERED]" + if thing_filter.filtered?(var) + "#{var}=#{thing_filter.label}" else "#{var}=#{instance_variable_get(var).inspect}" end diff --git a/lib/oauth2/sanitized_logger.rb b/lib/oauth2/sanitized_logger.rb new file mode 100644 index 00000000..3ae9ec1e --- /dev/null +++ b/lib/oauth2/sanitized_logger.rb @@ -0,0 +1,242 @@ +# frozen_string_literal: true + +module OAuth2 + # Logger wrapper that redacts sensitive values from debug output before + # delegating to the underlying logger instance. + # + # This class is intentionally narrow in scope: it only sanitizes string + # messages emitted through the debug logging path and leaves request/response + # behavior unchanged. + # + # The underlying {ThingFilter} is initialized once when the logger wrapper is + # created, so later config changes do not alter the behavior of existing + # logger instances. + class SanitizedLogger + # Create a new sanitized logger wrapper. + # + # @param [#add, #debug, #info, #warn, #error, #fatal, #unknown] logger + # The underlying logger instance that will receive sanitized messages. + # + # The debug filtering key list and replacement label are snapshotted from + # `OAuth2.config` during initialization. + def initialize(logger) + @logger = logger + @thing_filter = ThingFilter.new( + OAuth2.config[:filtered_debug_keys], + label: OAuth2.config[:filtered_label], + ) + end + + # Add a log entry after sanitizing any string payloads. + # + # @param [Integer, Symbol, String, nil] severity Logger severity + # @param [Object, nil] message Optional log message + # @param [Object, nil] progname Optional program name + # @yieldreturn [Object] Deferred log message + # @return [Object] The underlying logger result + def add(severity, message = nil, progname = nil) + if block_given? + @logger.add(severity, sanitize(message), sanitize(progname)) { sanitize(yield) } + else + @logger.add(severity, sanitize(message), sanitize(progname)) + end + end + + # Append a message to the underlying logger after sanitization. + # + # @param [String] message Message to append + # @return [Object] The underlying logger result + def <<(message) + @logger << sanitize(message) + end + + # Log a debug message after sanitization. + # + # @param [Object, nil] progname Optional program name + # @yieldreturn [Object] Deferred log message + # @return [Object] The underlying logger result + def debug(progname = nil, &block) + log(:debug, progname, &block) + end + + # Log an info message after sanitization. + # + # @param [Object, nil] progname Optional program name + # @yieldreturn [Object] Deferred log message + # @return [Object] The underlying logger result + def info(progname = nil, &block) + log(:info, progname, &block) + end + + # Log a warning message after sanitization. + # + # @param [Object, nil] progname Optional program name + # @yieldreturn [Object] Deferred log message + # @return [Object] The underlying logger result + def warn(progname = nil, &block) + log(:warn, progname, &block) + end + + # Log an error message after sanitization. + # + # @param [Object, nil] progname Optional program name + # @yieldreturn [Object] Deferred log message + # @return [Object] The underlying logger result + def error(progname = nil, &block) + log(:error, progname, &block) + end + + # Log a fatal message after sanitization. + # + # @param [Object, nil] progname Optional program name + # @yieldreturn [Object] Deferred log message + # @return [Object] The underlying logger result + def fatal(progname = nil, &block) + log(:fatal, progname, &block) + end + + # Log an unknown-severity message after sanitization. + # + # @param [Object, nil] progname Optional program name + # @yieldreturn [Object] Deferred log message + # @return [Object] The underlying logger result + def unknown(progname = nil, &block) + log(:unknown, progname, &block) + end + + # Close the underlying logger if supported. + # + # @return [void] + def close + @logger.close if @logger.respond_to?(:close) + end + + # Access the formatter of the underlying logger if supported. + # + # @return [Object, nil] + def formatter + @logger.formatter if @logger.respond_to?(:formatter) + end + + # Set the formatter of the underlying logger if supported. + # + # @param [Object] formatter Formatter object + # @return [void] + def formatter=(formatter) + @logger.formatter = formatter if @logger.respond_to?(:formatter=) + end + + # Access the logger level if supported. + # + # @return [Object, nil] + def level + @logger.level if @logger.respond_to?(:level) + end + + # Set the logger level if supported. + # + # @param [Object] level Logger level + # @return [void] + def level=(level) + @logger.level = level if @logger.respond_to?(:level=) + end + + # Access the logger progname if supported. + # + # @return [Object, nil] + def progname + @logger.progname if @logger.respond_to?(:progname) + end + + # Set the logger progname if supported. + # + # @param [Object] progname Logger progname + # @return [void] + def progname=(progname) + @logger.progname = progname if @logger.respond_to?(:progname=) + end + + # Report support for methods provided by the wrapped logger. + # + # @param [Symbol] method_name Method name to check + # @param [Boolean] include_private Whether private methods are considered + # @return [Boolean] + def respond_to_missing?(method_name, include_private = false) + @logger.respond_to?(method_name, include_private) || super + end + + # Delegate unsupported methods to the wrapped logger. + # + # @param [Symbol] method_name Method to invoke + # @param [Array] args Method arguments + # @yield Deferred block forwarded to the wrapped logger + # @return [Object] The delegated result + def method_missing(method_name, *args, &block) + return super unless @logger.respond_to?(method_name) + + @logger.public_send(method_name, *args, &block) + end + + private + + # Dispatch a severity-specific log call after sanitization. + # + # @param [Symbol] level Logger method name + # @param [Object, nil] progname Optional program name + # @yieldreturn [Object] Deferred log message + # @return [Object] The underlying logger result + def log(level, progname = nil) + if block_given? + @logger.public_send(level, sanitize(progname)) { sanitize(yield) } + else + @logger.public_send(level, sanitize(progname)) + end + end + + # Sanitize a logger message when it is a String. + # + # @param [Object] message Potential logger payload + # @return [Object] Unchanged non-String payloads, sanitized String payloads + def sanitize(message) + return message unless message.is_a?(String) + + sanitized = message.dup + sanitized = sanitize_authorization_header(sanitized) + sanitized = sanitize_json_pairs(sanitized) + sanitize_form_and_query_pairs(sanitized) + end + + # The initialized thing filter used by this logger. + # + # This is a per-logger snapshot created during initialization. + # + # @return [ThingFilter] + attr_reader :thing_filter + + # Redact Authorization header values. + # + # @param [String] message Logger message + # @return [String] Sanitized logger message + def sanitize_authorization_header(message) + message.gsub(/(Authorization:\s*)(?:\"[^\"]*\"|[^\r\n]+)/i, "\\1\"#{thing_filter.label}\"") + end + + # Redact JSON-style values for configured sensitive key names. + # + # @param [String] message Logger message + # @return [String] Sanitized logger message + def sanitize_json_pairs(message) + message.gsub(/([\"'])(#{thing_filter.pattern_source})\1(\s*:\s*)([\"'])(.*?)\4/i) do + %(#{$1}#{$2}#{$1}#{$3}#{$4}#{thing_filter.label}#{$4}) + end + end + + # Redact form-encoded and query-string values for configured sensitive key names. + # + # @param [String] message Logger message + # @return [String] Sanitized logger message + def sanitize_form_and_query_pairs(message) + message.gsub(/(\b(?:#{thing_filter.pattern_source})=)([^&\s\"]+)/i, "\\1#{thing_filter.label}") + end + end +end diff --git a/lib/oauth2/thing_filter.rb b/lib/oauth2/thing_filter.rb new file mode 100644 index 00000000..0bd40ce6 --- /dev/null +++ b/lib/oauth2/thing_filter.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +module OAuth2 + # Small value object for matching and filtering named things. + # + # Used by multiple filtering surfaces in the library, such as inspected + # object attributes and debug-log key filtering. + # + # `ThingFilter` snapshots and duplicates its inputs on initialization so later + # mutation of caller-owned arrays or strings does not affect existing filter + # instances. + class ThingFilter + # Create a new filter. + # + # @param [Enumerable<#to_s>] things Names that should be filtered + # @param [String] label Replacement label to use for filtered values + # + # The provided values are duplicated and frozen so the filter remains + # stable for the lifetime of the object. + def initialize(things, label:) + @things = Array(things).map { |thing| thing.to_s.dup.freeze }.freeze + @label = label.to_s.dup.freeze + @pattern_source = Regexp.union(@things).source.freeze + end + + # The configured names that should be filtered. + # + # @return [Array] + attr_reader :things + + # The configured replacement label. + # + # @return [String] + attr_reader :label + + # True when the provided name matches any configured filter entry. + # + # Matching is substring-based so it works naturally with instance-variable + # names used by `#inspect`, such as `@secret` matching `secret`. + # + # @param [#to_s] thing_name Candidate thing name + # @return [Boolean] + def filtered?(thing_name) + thing_name_str = thing_name.to_s + things.any? { |thing| thing_name_str.include?(thing) } + end + + # Build a regular-expression source for the configured thing names. + # + # Useful when a filtering surface needs regex-based replacement rather than + # direct name checks. + # + # @return [String] + attr_reader :pattern_source + end +end diff --git a/sig/oauth2/filtered_attributes.rbs b/sig/oauth2/filtered_attributes.rbs index da7e30f6..f2e2313f 100644 --- a/sig/oauth2/filtered_attributes.rbs +++ b/sig/oauth2/filtered_attributes.rbs @@ -1,6 +1,11 @@ module OAuth2 module FilteredAttributes + module InitializerMethods + def initialize: (*untyped args) { () -> untyped } -> untyped + end + def self.included: (untyped) -> untyped - def filtered_attributes: (*String) -> void + def filtered_attributes: (*(String | Symbol)) -> void + def thing_filter: () -> OAuth2::ThingFilter end end diff --git a/sig/oauth2/sanitized_logger.rbs b/sig/oauth2/sanitized_logger.rbs new file mode 100644 index 00000000..3ac31a9d --- /dev/null +++ b/sig/oauth2/sanitized_logger.rbs @@ -0,0 +1,32 @@ +module OAuth2 + class SanitizedLogger + def initialize: (untyped logger) -> void + + def add: (untyped severity, ?untyped message, ?untyped progname) { () -> untyped } -> untyped + def <<: (String message) -> untyped + def debug: (?untyped progname) { () -> untyped } -> untyped + def info: (?untyped progname) { () -> untyped } -> untyped + def warn: (?untyped progname) { () -> untyped } -> untyped + def error: (?untyped progname) { () -> untyped } -> untyped + def fatal: (?untyped progname) { () -> untyped } -> untyped + def unknown: (?untyped progname) { () -> untyped } -> untyped + def close: () -> void + def formatter: () -> untyped + def formatter=: (untyped formatter) -> void + def level: () -> untyped + def level=: (untyped level) -> void + def progname: () -> untyped + def progname=: (untyped progname) -> void + def respond_to_missing?: (Symbol method_name, ?bool include_private) -> bool + def method_missing: (Symbol method_name, *untyped args) { () -> untyped } -> untyped + + private + + def log: (Symbol level, ?untyped progname) { () -> untyped } -> untyped + def sanitize: (untyped message) -> untyped + def thing_filter: () -> OAuth2::ThingFilter + def sanitize_authorization_header: (String message) -> String + def sanitize_json_pairs: (String message) -> String + def sanitize_form_and_query_pairs: (String message) -> String + end +end diff --git a/sig/oauth2/thing_filter.rbs b/sig/oauth2/thing_filter.rbs new file mode 100644 index 00000000..4e341d95 --- /dev/null +++ b/sig/oauth2/thing_filter.rbs @@ -0,0 +1,10 @@ +module OAuth2 + class ThingFilter + attr_reader things: Array[String] + attr_reader label: String + + def initialize: (Enumerable[untyped] things, label: String) -> void + def filtered?: (untyped thing_name) -> bool + def pattern_source: () -> String + end +end diff --git a/spec/oauth2/authenticator_spec.rb b/spec/oauth2/authenticator_spec.rb index e39a28c5..88a20a8e 100644 --- a/spec/oauth2/authenticator_spec.rb +++ b/spec/oauth2/authenticator_spec.rb @@ -170,5 +170,22 @@ expect(subject.inspect).to include("@secret=\"bar\"") end end + + context "when config changes after initialization" do + before do + @original_filtered_label = OAuth2.config[:filtered_label] + subject + OAuth2.config[:filtered_label] = "[REDACTED]" + end + + after do + OAuth2.config[:filtered_label] = @original_filtered_label + end + + it "keeps using the initialized filter label" do + expect(subject.inspect).to include("@secret=[FILTERED]") + expect(subject.inspect).not_to include("@secret=[REDACTED]") + end + end end end diff --git a/spec/oauth2/client_spec.rb b/spec/oauth2/client_spec.rb index 45d786ec..66523585 100644 --- a/spec/oauth2/client_spec.rb +++ b/spec/oauth2/client_spec.rb @@ -204,7 +204,7 @@ end describe "custom headers" do - context "string key headers" do + context "with string key headers" do it "adds the custom headers to request" do client = described_class.new("abc", "def", site: "https://api.example.com", auth_scheme: :request_body) do |builder| builder.adapter :test do |stub| @@ -219,7 +219,7 @@ end end - context "symbol key headers" do + context "with symbol key headers" do it "adds the custom headers to request" do client = described_class.new("abc", "def", site: "https://api.example.com", auth_scheme: :request_body) do |builder| builder.adapter :test do |stub| @@ -234,7 +234,7 @@ end end - context "string key custom headers with basic auth" do + context "with string key custom headers and basic auth" do it "adds the custom headers to request" do client = described_class.new("abc", "def", site: "https://api.example.com") do |builder| builder.adapter :test do |stub| @@ -249,7 +249,7 @@ end end - context "symbol key custom headers with basic auth" do + context "with symbol key custom headers and basic auth" do it "adds the custom headers to request" do client = described_class.new("abc", "def", site: "https://api.example.com") do |builder| builder.adapter :test do |stub| @@ -287,16 +287,153 @@ end.not_to raise_error end - it "prints both request and response bodies to STDOUT" do + it "prints useful non-sensitive request and response details to STDOUT" do printed = capture(:stdout) do subject.request(:get, "/success") - subject.request(:get, "/reflect", body: "this is magical") + subject.request(:get, "/reflect", body: "this is harmless") end expect(printed).to match "request: GET https://api.example.com/success" expect(printed).to match "response: Content-Type:" expect(printed).to match "response: yay" - expect(printed).to match "request: this is magical" - expect(printed).to match "response: this is magical" + expect(printed).to match "request: this is harmless" + expect(printed).to match "response: this is harmless" + end + + it "redacts Authorization header values from STDOUT" do + secret = "super-secret-token" + + printed = capture(:stdout) do + subject.request(:get, "/success", headers: {"Authorization" => "Bearer #{secret}"}) + end + + expect(printed).to include("request: GET https://api.example.com/success") + expect(printed).not_to include(secret) + expect(printed).not_to include("Bearer #{secret}") + expect(printed).to match(/FILTERED|REDACTED/) + end + + it "redacts form-encoded secret fields from STDOUT" do + printed = capture(:stdout) do + subject.request(:post, "/reflect", body: "access_token=abc123&client_secret=shhh&grant_type=refresh_token") + end + + expect(printed).not_to include("abc123") + expect(printed).not_to include("shhh") + expect(printed).to include("grant_type") + expect(printed).to match(/FILTERED|REDACTED/) + end + + it "redacts token material in JSON responses from STDOUT" do + client = stubbed_client(auth_scheme: :request_body) do |stub| + stub.post("/oauth/token") do + [ + 200, + {"Content-Type" => "application/json"}, + JSON.dump( + "access_token" => "the-access-token", + "refresh_token" => "the-refresh-token", + "id_token" => "the-id-token", + "token_type" => "Bearer", + ), + ] + end + end + + printed = capture(:stdout) do + client.get_token({}) + end + + expect(printed).not_to include("the-access-token") + expect(printed).not_to include("the-refresh-token") + expect(printed).not_to include("the-id-token") + expect(printed).to include("token_type") + expect(printed).to match(/FILTERED|REDACTED/) + end + + it "redacts query-string secret fields from STDOUT" do + printed = capture(:stdout) do + subject.request(:get, "/success", params: {"access_token" => "abc123", "state" => "ok-state"}) + end + + expect(printed).not_to include("abc123") + expect(printed).to include("ok-state") + expect(printed).to match(/FILTERED|REDACTED/) + end + + it "redacts basic auth credentials from STDOUT" do + client = stubbed_client do |stub| + stub.post("/oauth/token") do + [200, {"Content-Type" => "application/json"}, JSON.dump("access_token" => "the-token")] + end + end + + printed = capture(:stdout) do + client.get_token({}) + end + + expect(printed).not_to include(OAuth2::Authenticator.encode_basic_auth("abc", "def")) + expect(printed).not_to include("def") + expect(printed).to match(/FILTERED|REDACTED/) + end + + it "redacts code_verifier and assertion fields from STDOUT" do + printed = capture(:stdout) do + subject.request(:post, "/reflect", body: "code_verifier=pkce-secret&assertion=jwt-assertion-material&grant_type=authorization_code") + end + + expect(printed).not_to include("pkce-secret") + expect(printed).not_to include("jwt-assertion-material") + expect(printed).to include("grant_type") + expect(printed).to match(/FILTERED|REDACTED/) + end + + it "redacts revoke token values from STDOUT" do + printed = capture(:stdout) do + subject.revoke_token("banana-foster") + end + + expect(printed).not_to include("banana-foster") + expect(printed).to include("/oauth/revoke") + expect(printed).to match(/FILTERED|REDACTED/) + end + + it "safely redacts obvious secrets in opaque non-JSON response bodies" do + client = stubbed_client do |stub| + stub.get("/opaque_secret") do + [200, {"Content-Type" => "text/plain"}, "access_token=abc123¬e=hello"] + end + end + + printed = capture(:stdout) do + client.request(:get, "/opaque_secret") + end + + expect(printed).not_to include("abc123") + expect(printed).to include("note=hello") + expect(printed).to match(/FILTERED|REDACTED/) + end + + it "keeps using the initialized debug filter after config changes" do + subject.connection + + original_filtered_label = OAuth2.config[:filtered_label] + original_filtered_debug_keys = OAuth2.config[:filtered_debug_keys] + + begin + OAuth2.config[:filtered_label] = "[REDACTED]" + OAuth2.config[:filtered_debug_keys] = [] + + printed = capture(:stdout) do + subject.request(:get, "/success", headers: {"Authorization" => "Bearer super-secret-token"}) + end + + expect(printed).not_to include("super-secret-token") + expect(printed).to include("[FILTERED]") + expect(printed).not_to include("[REDACTED]") + ensure + OAuth2.config[:filtered_label] = original_filtered_label + OAuth2.config[:filtered_debug_keys] = original_filtered_debug_keys + end end end @@ -1172,7 +1309,7 @@ def contains_token?(hash) expect(printed).to eq(msg) end - context "on request" do + context "when on request" do subject(:printed) do capture(:stderr) do client.get_token({}, {}, extract_access_token) diff --git a/spec/oauth2/error_spec.rb b/spec/oauth2/error_spec.rb index 281d93f8..c2dc6400 100644 --- a/spec/oauth2/error_spec.rb +++ b/spec/oauth2/error_spec.rb @@ -95,7 +95,7 @@ def to_str skip_for(encoding.merge(engine: "jruby")) # See https://bibwild.wordpress.com/2013/03/12/removing-illegal-bytes-for-encoding-in-ruby-1-9-strings/ - raise "Invalid characters not replaced" unless subject.message.include?("� invalid �") + expect(subject.message).to include("� invalid �") # This will fail if {:invalid => replace} is not passed into `encode` end end @@ -106,7 +106,7 @@ def to_str end it "replaces them" do - raise "Undefined characters not replaced" unless subject.message.include?("tea �") + expect(subject.message).to include("tea �") # This will fail if {:undef => replace} is not passed into `encode` end end @@ -243,7 +243,7 @@ def to_str skip_for(encoding.merge(engine: "jruby")) # See https://bibwild.wordpress.com/2013/03/12/removing-illegal-bytes-for-encoding-in-ruby-1-9-strings/ - raise "Invalid characters not replaced" unless subject.message.include?("� invalid �") + expect(subject.message).to include("� invalid �") # This will fail if {:invalid => replace} is not passed into `encode` end end @@ -254,7 +254,7 @@ def to_str end it "replaces them" do - raise "Undefined characters not replaced" unless subject.message.include?("tea �") + expect(subject.message).to include("tea �") # This will fail if {:undef => replace} is not passed into `encode` end end @@ -317,7 +317,7 @@ def to_str skip_for(encoding.merge(engine: "jruby")) # See https://bibwild.wordpress.com/2013/03/12/removing-illegal-bytes-for-encoding-in-ruby-1-9-strings/ - raise "Invalid characters not replaced" unless subject.message.include?("� invalid �") + expect(subject.message).to include("� invalid �") # This will fail if {:invalid => replace} is not passed into `encode` end end @@ -378,7 +378,7 @@ def to_str skip_for(encoding.merge(engine: "jruby")) # See https://bibwild.wordpress.com/2013/03/12/removing-illegal-bytes-for-encoding-in-ruby-1-9-strings/ - raise "Invalid characters not replaced" unless subject.message.include?("� invalid �") + expect(subject.message).to include("� invalid �") # This will fail if {:invalid => replace} is not passed into `encode` end end @@ -389,7 +389,7 @@ def to_str end it "replaces them" do - raise "Undefined characters not replaced" unless subject.message.include?("tea �") + expect(subject.message).to include("tea �") # This will fail if {:undef => replace} is not passed into `encode` end end diff --git a/spec/oauth2/thing_filter_spec.rb b/spec/oauth2/thing_filter_spec.rb new file mode 100644 index 00000000..84564ea9 --- /dev/null +++ b/spec/oauth2/thing_filter_spec.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true + +RSpec.describe OAuth2::ThingFilter do + describe "#initialize" do + it "does not freeze caller-owned string inputs" do + things = [String.new("secret")] + label = String.new("[FILTERED]") + + described_class.new(things, label: label) + + expect(things.first).not_to be_frozen + expect(label).not_to be_frozen + end + + it "does not track later in-place mutation of original string inputs" do + original_thing = String.new("secret") + original_label = String.new("[FILTERED]") + + filter = described_class.new([original_thing], label: original_label) + + original_thing.replace("token") + original_label.replace("[REDACTED]") + + expect(filter.filtered?("@secret")).to be(true) + expect(filter.filtered?("@token")).to be(false) + expect(filter.label).to eq("[FILTERED]") + end + end + + describe "FilteredAttributes integration" do + let(:poro_class) do + Class.new do + include OAuth2::FilteredAttributes + + attr_reader :secret, :name + filtered_attributes :secret + + def initialize(secret, name) + @secret = secret + @name = name + end + end + end + + let(:instance) { poro_class.new("super-secret", "bolt") } + + it "filters configured attributes in inspect" do + expect(instance.inspect).to include("@secret=[FILTERED]") + expect(instance.inspect).to include('@name="bolt"') + end + + it "can be duplicated" do + copy = instance.dup + + expect(copy).not_to equal(instance) + expect(copy.inspect).to include("@secret=[FILTERED]") + expect(copy.inspect).to include('@name="bolt"') + end + + it "can be cloned" do + copy = instance.clone + + expect(copy).not_to equal(instance) + expect(copy.inspect).to include("@secret=[FILTERED]") + expect(copy.inspect).to include('@name="bolt"') + end + end +end