Top Related Projects
OmniAuth is a flexible authentication system utilizing Rack middleware.
Doorkeeper is an OAuth 2 provider for Ruby on Rails / Grape.
A Ruby wrapper for OAuth 2.0 protocol, including OIDC
Library for stubbing and setting expectations on HTTP requests in Ruby.
Simple Rails app configuration
A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
Quick Overview
OAuth2 is a Ruby wrapper for the OAuth 2.0 protocol, providing a simple and flexible way to integrate OAuth 2.0 authentication into Ruby applications. It supports various grant types and offers a high level of customization for different OAuth 2.0 providers.
Pros
- Easy to use and integrate with Ruby applications
- Supports multiple grant types (authorization code, client credentials, etc.)
- Highly customizable for different OAuth 2.0 providers
- Well-maintained and actively developed
Cons
- Limited documentation for advanced use cases
- Some users report occasional issues with certain OAuth providers
- Dependency on Faraday gem may not be ideal for all projects
- Learning curve for OAuth 2.0 concepts can be steep for beginners
Code Examples
- Creating an OAuth2::Client instance:
require 'oauth2'
client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.com')
- Generating an authorization URL:
auth_url = client.auth_code.authorize_url(redirect_uri: 'http://localhost:8080/callback')
- Exchanging an authorization code for an access token:
token = client.auth_code.get_token('authorization_code', redirect_uri: 'http://localhost:8080/callback')
- Making an authenticated API request:
response = token.get('/api/user')
user_info = JSON.parse(response.body)
Getting Started
- Install the gem:
gem install oauth2
- Create a client instance:
require 'oauth2'
client = OAuth2::Client.new('your_client_id', 'your_client_secret',
site: 'https://example.com',
authorize_url: '/oauth/authorize',
token_url: '/oauth/token'
)
- Generate an authorization URL and redirect the user:
auth_url = client.auth_code.authorize_url(redirect_uri: 'http://your-app.com/callback')
# Redirect the user to auth_url
- Exchange the authorization code for an access token:
token = client.auth_code.get_token('authorization_code_from_callback', redirect_uri: 'http://your-app.com/callback')
- Use the access token to make authenticated requests:
response = token.get('/api/protected_resource')
Competitor Comparisons
OmniAuth is a flexible authentication system utilizing Rack middleware.
Pros of OmniAuth
- Provides a standardized interface for multiple authentication providers
- Offers a wide range of pre-built strategies for popular services
- Simplifies the integration of multiple authentication methods in a single application
Cons of OmniAuth
- Requires additional configuration for each authentication provider
- May introduce complexity when handling different data structures from various providers
- Slightly higher learning curve for developers new to the concept of authentication strategies
Code Comparison
OAuth2:
client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.com')
token = client.auth_code.get_token('authorization_code', redirect_uri: 'https://example.com/callback')
response = token.get('/api/resource')
OmniAuth:
use OmniAuth::Builder do
provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
end
get '/auth/:provider/callback' do
auth = request.env['omniauth.auth']
# Handle authentication data
end
Both OAuth2 and OmniAuth are popular Ruby gems for handling authentication, but they serve different purposes. OAuth2 focuses specifically on the OAuth 2.0 protocol, providing a low-level client for interacting with OAuth 2.0 providers. OmniAuth, on the other hand, offers a higher-level abstraction for multiple authentication providers, including OAuth 2.0, OAuth 1.0, and others.
OAuth2 is more suitable for developers who need fine-grained control over the OAuth 2.0 flow and want to work directly with the protocol. OmniAuth is better suited for applications that require support for multiple authentication providers and prefer a unified interface for handling various authentication strategies.
Doorkeeper is an OAuth 2 provider for Ruby on Rails / Grape.
Pros of Doorkeeper
- Full-featured OAuth2 provider solution for Rails applications
- Extensive documentation and active community support
- Built-in support for various OAuth2 flows and token management
Cons of Doorkeeper
- Specific to Rails applications, limiting its use in other Ruby frameworks
- Steeper learning curve for beginners due to its comprehensive feature set
Code Comparison
OAuth2 (Client-side usage):
client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.com')
token = client.client_credentials.get_token
response = token.get('/api/resource')
Doorkeeper (Server-side configuration):
Doorkeeper.configure do
resource_owner_authenticator do
User.find_by_id(session[:user_id]) || redirect_to(login_url)
end
access_token_expires_in 2.hours
end
OAuth2 is a lightweight OAuth2 client library, while Doorkeeper is a comprehensive OAuth2 provider solution for Rails applications. OAuth2 focuses on client-side interactions, making it easier to integrate OAuth2 authentication in various Ruby applications. Doorkeeper, on the other hand, provides a full server-side implementation for Rails, including database migrations, customizable views, and extensive configuration options.
While OAuth2 offers flexibility across different Ruby frameworks, Doorkeeper excels in providing a robust OAuth2 provider solution specifically for Rails applications. The choice between the two depends on whether you need a client-side library or a full-featured OAuth2 provider for your Rails application.
A Ruby wrapper for OAuth 2.0 protocol, including OIDC
Pros of oauth2
- More actively maintained with recent updates
- Larger community and contributor base
- Better documentation and examples
Cons of oauth2
- Slightly more complex API
- May have more dependencies
- Potentially steeper learning curve for beginners
Code Comparison
oauth2:
client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.com')
token = client.client_credentials.get_token
response = token.get('/api/resource')
oauth2:
client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.com')
token = client.client_credentials.get_token
response = token.get('/api/resource')
The code snippets for both libraries are identical in this basic usage scenario. Both use the same method names and structure for creating a client, obtaining a token, and making a request.
In practice, the main differences between the two libraries lie in their implementation details, additional features, and how they handle various OAuth 2.0 flows. The oauth2 library may offer more advanced options and configurations, while oauth2 might provide a simpler interface for basic use cases.
When choosing between the two, consider factors such as project requirements, community support, and long-term maintenance. The oauth2 library is generally recommended due to its active development and larger ecosystem.
Library for stubbing and setting expectations on HTTP requests in Ruby.
Pros of WebMock
- Focused on HTTP request stubbing and mocking, providing more comprehensive features for this specific use case
- Easier to set up and use for testing HTTP interactions in Ruby applications
- More actively maintained with frequent updates and contributions
Cons of WebMock
- Limited to HTTP mocking and stubbing, while OAuth2 provides broader OAuth 2.0 functionality
- May require additional setup when used in conjunction with other HTTP libraries
- Potential for overuse in tests, leading to less realistic test scenarios
Code Comparison
WebMock example:
stub_request(:get, "https://api.example.com/users")
.to_return(status: 200, body: '{"users": []}', headers: {'Content-Type' => 'application/json'})
OAuth2 example:
client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.com')
token = client.client_credentials.get_token
response = token.get('/api/resource')
While WebMock focuses on stubbing HTTP requests for testing, OAuth2 provides a client for OAuth 2.0 authorization. WebMock is more suitable for general HTTP request mocking, whereas OAuth2 is specifically designed for implementing OAuth 2.0 authentication flows in Ruby applications.
Simple Rails app configuration
Pros of Figaro
- Simple configuration management for Ruby applications
- Easily manage environment variables and sensitive information
- Lightweight and focused on a single purpose
Cons of Figaro
- Limited to configuration management, unlike OAuth2's broader authentication scope
- May require additional setup for non-Rails projects
- Less actively maintained compared to OAuth2
Code Comparison
Figaro configuration example:
# config/application.yml
GMAIL_USERNAME: "your_username@gmail.com"
GMAIL_PASSWORD: "your_password"
OAuth2 usage example:
client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.org')
token = client.client_credentials.get_token
response = token.get('/api/resource')
Summary
Figaro is a lightweight gem focused on configuration management, making it easy to handle environment variables and sensitive information in Ruby applications. It's particularly useful for Rails projects but may require additional setup for other Ruby frameworks.
OAuth2, on the other hand, is a more comprehensive library for handling OAuth 2.0 authentication. It provides a broader set of features related to authentication and authorization, making it suitable for applications that need to interact with OAuth 2.0 providers.
While Figaro excels in simplifying configuration management, OAuth2 is better suited for applications requiring robust authentication capabilities. The choice between the two depends on the specific needs of your project.
A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
Pros of ruby-jwt
- Simpler implementation for stateless authentication
- Lightweight and faster processing due to self-contained tokens
- Better suited for microservices architectures
Cons of ruby-jwt
- Limited built-in security features compared to OAuth 2.0
- Requires careful implementation to avoid security vulnerabilities
- Less flexibility for managing user permissions and scopes
Code Comparison
ruby-jwt:
require 'jwt'
payload = { data: 'test' }
token = JWT.encode payload, 'secret', 'HS256'
decoded_token = JWT.decode token, 'secret', true, { algorithm: 'HS256' }
oauth2:
require 'oauth2'
client = OAuth2::Client.new('client_id', 'client_secret', site: 'https://example.org')
token = client.client_credentials.get_token
response = token.get('/api/resource')
Summary
ruby-jwt is more suitable for simple, stateless authentication scenarios, while oauth2 offers a more comprehensive solution for authorization and secure API access. ruby-jwt is lighter and faster, but oauth2 provides better security features and flexibility for managing user permissions. The choice between the two depends on the specific requirements of your application and the level of security and complexity needed for your authentication and authorization processes.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ð OAuth2
OAuth 2.0 is the industry-standard protocol for authorization. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. This is a RubyGem for implementing OAuth 2.0 clients (not servers) in Ruby applications.
Federated DVCS Repository | Status | Issues | PRs | Wiki | CI | Discussions |
---|---|---|---|---|---|---|
𧪠oauth-xx/oauth2 on GitLab | The Truth | ð | ð | ð | ð Tiny Matrix | â |
ð§ oauth-xx/oauth2 on CodeBerg | An Ethical Mirror (Donate) | â | ð | â | âï¸ No Matrix | â |
ð oauth-xx/oauth2 on GitHub | A Dirty Mirror | ð | ð | â | ð¯ Full Matrix | â |
𤼠OAuth Ruby Google Group | "Active" | â | â | â | â | ð |
ð®ï¸ Discord Server | Let's | talk | about | this | library! |
Upgrading Runtime Gem Dependencies
This project sits underneath a large portion of the authorization systems on the internet. According to GitHub's project tracking, which I believe only reports on public projects, 100,000+ projects, and 500+ packages depend on this project.
That means it is painful for the Ruby community when this gem forces updates to its runtime dependencies.
As a result, great care, and a lot of time, have been invested to ensure this gem is working with all the leading versions per each minor version of Ruby of all the runtime dependencies it can install with.
What does that mean specifically for the runtime dependencies?
We have 100% test coverage of lines and branches, and this test suite runs across a large matrix covering the latest patch for each of the following minor versions:
- MRI Ruby @ v2.3, v2.4, v2.5, v2.6, v2.7, v3.0, v3.1, v3.2, v3.3, v3.4, HEAD
- NOTE: This gem will still install on ruby v2.2, but vanilla GitHub Actions no longer supports testing against it, so YMMV.
- JRuby @ v9.2, v9.3, v9.4, v10.0, HEAD
- TruffleRuby @ v23.1, v24.1, HEAD
- gem
faraday
@ v0, v1, v2, HEAD â©ï¸ lostisland/faraday - gem
jwt
@ v1, v2, v3, HEAD â©ï¸ jwt/ruby-jwt - gem
logger
@ v1.2, v1.5, v1.7, HEAD â©ï¸ ruby/logger - gem
multi_xml
@ v0.5, v0.6, v0.7, HEAD â©ï¸ sferik/multi_xml - gem
rack
@ v1.2, v1.6, v2, v3, HEAD â©ï¸ rack/rack - gem
snaky_hash
@ v2, HEAD â©ï¸ oauth-xx/snaky_hash - gem
version_gem
@ v1, HEAD â©ï¸ oauth-xx/version_gem
The last two were extracted from this gem. They are part of the oauth-xx
org,
and are developed in tight collaboration with this gem.
Also, where reasonable, tested against the runtime dependencies of those dependencies:
- gem
hashie
@ v0, v1, v2, v3, v4, v5, HEAD â©ï¸ hashie/hashie
You should upgrade this gem with confidence*.
- This gem follows a strict & correct (according to the maintainer of SemVer; more info) interpretation of SemVer.
- Dropping support for any of the runtime dependency versions above will be a major version bump.
- If you aren't on one of the minor versions above, make getting there a priority.
- You should upgrade the dependencies of this gem with confidence*.
- Please do upgrade, and then, when it goes smooth as butter please sponsor me. Thanks!
* MIT license; I am unable to make guarantees.
ð Test matrix brought to you by | ð appraisal++ |
---|---|
Adds back support for old Rubies | ⨠appraisal PR #250 |
Adds support for eval_gemfile | ⨠appraisal PR #248 |
Please review | my PRs! |
Standard Library Dependencies
The various versions of each are tested via the Ruby test matrix, along with whatever Ruby includes them.
- base64
- cgi
- json
- time
- logger (removed from stdlib in Ruby 3.5 so added as runtime dependency in v2.0.10)
If you use a gem version it should work fine!
Quick Usage Example for AI and Copy / Pasting
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.
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",
). # The base path for token_url when it is relative
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!
If any of the above makes you uncomfortable, you may be in the wrong place. One of these might be what you are looking for:
- OAuth 2.0 Spec
- doorkeeper gem for OAuth 2.0 server/provider implementation.
- oauth sibling gem for OAuth 1.0 implementations in Ruby.
ð¡ Info you can shake a stick at
Tokens to Remember | |
---|---|
Works with JRuby | |
Works with Truffle Ruby | |
Works with MRI Ruby 3 | |
Works with MRI Ruby 2 | |
Source | |
Documentation | |
Compliance | |
Style | |
Support | |
Enterprise Support | ð¡Subscribe for support guarantees covering all 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! |
Comrade BDFL ðï¸ | |
... ð |
ð Release Documentation
Version 2.0.x
2.0.x CHANGELOG and README
Version | Release Date | CHANGELOG | README |
---|---|---|---|
2.0.12 | 2025-05-31 | v2.0.12 CHANGELOG | v2.0.12 README |
2.0.11 | 2025-05-23 | v2.0.11 CHANGELOG | v2.0.11 README |
2.0.10 | 2025-05-17 | v2.0.10 CHANGELOG | v2.0.10 README |
2.0.9 | 2022-09-16 | v2.0.9 CHANGELOG | v2.0.9 README |
2.0.8 | 2022-09-01 | v2.0.8 CHANGELOG | v2.0.8 README |
2.0.7 | 2022-08-22 | v2.0.7 CHANGELOG | v2.0.7 README |
2.0.6 | 2022-07-13 | v2.0.6 CHANGELOG | v2.0.6 README |
2.0.5 | 2022-07-07 | v2.0.5 CHANGELOG | v2.0.5 README |
2.0.4 | 2022-07-01 | v2.0.4 CHANGELOG | v2.0.4 README |
2.0.3 | 2022-06-28 | v2.0.3 CHANGELOG | v2.0.3 README |
2.0.2 | 2022-06-24 | v2.0.2 CHANGELOG | v2.0.2 README |
2.0.1 | 2022-06-22 | v2.0.1 CHANGELOG | v2.0.1 README |
2.0.0 | 2022-06-21 | v2.0.0 CHANGELOG | v2.0.0 README |
Older Releases
1.4.x CHANGELOGs and READMEs
Version | Release Date | CHANGELOG | README |
---|---|---|---|
1.4.11 | Sep 16, 2022 | v1.4.11 CHANGELOG | v1.4.11 README |
1.4.10 | Jul 1, 2022 | v1.4.10 CHANGELOG | v1.4.10 README |
1.4.9 | Feb 20, 2022 | v1.4.9 CHANGELOG | v1.4.9 README |
1.4.8 | Feb 18, 2022 | v1.4.8 CHANGELOG | v1.4.8 README |
1.4.7 | Mar 19, 2021 | v1.4.7 CHANGELOG | v1.4.7 README |
1.4.6 | Mar 19, 2021 | v1.4.6 CHANGELOG | v1.4.6 README |
1.4.5 | Mar 18, 2021 | v1.4.5 CHANGELOG | v1.4.5 README |
1.4.4 | Feb 12, 2020 | v1.4.4 CHANGELOG | v1.4.4 README |
1.4.3 | Jan 29, 2020 | v1.4.3 CHANGELOG | v1.4.3 README |
1.4.2 | Oct 1, 2019 | v1.4.2 CHANGELOG | v1.4.2 README |
1.4.1 | Oct 13, 2018 | v1.4.1 CHANGELOG | v1.4.1 README |
1.4.0 | Jun 9, 2017 | v1.4.0 CHANGELOG | v1.4.0 README |
1.3.x Readmes
Version | Release Date | Readme |
---|---|---|
1.3.1 | Mar 3, 2017 | https://gitlab.com/oauth-xx/oauth2/-/blob/v1.3.1/README.md |
1.3.0 | Dec 27, 2016 | https://gitlab.com/oauth-xx/oauth2/-/blob/v1.3.0/README.md |
≤= 1.2.x Readmes (2016 and before)
Version | Release Date | Readme |
---|---|---|
1.2.0 | Jun 30, 2016 | https://gitlab.com/oauth-xx/oauth2/-/blob/v1.2.0/README.md |
1.1.0 | Jan 30, 2016 | https://gitlab.com/oauth-xx/oauth2/-/blob/v1.1.0/README.md |
1.0.0 | May 23, 2014 | https://gitlab.com/oauth-xx/oauth2/-/blob/v1.0.0/README.md |
< 1.0.0 | Find here | https://gitlab.com/oauth-xx/oauth2/-/tags |
⨠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
oauth2
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/oauth-xx/oauth2/main/certs/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
NOTE: Be prepared to track down certs for signed gems and add them the same way you added mine.
OAuth2 for Enterprise
Available as part of the Tidelift Subscription.
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. Learn more.
Security contact information
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
For more see SECURITY.md.
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 JWT
- 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)
- 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 toget_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 Version | Maintenance Branch | Targeted Support | Best Effort Support | Incidental Support | |
---|---|---|---|---|---|
1ï¸â£ | 2.0.x | main | 3.2, 3.3, 3.4 | 2.5, 2.6, 2.7, 3.0, 3.1 | 2.2, 2.3, 2.4 |
2ï¸â£ | 1.4.x | 1-4-stable | 3.2, 3.3, 3.4 | 2.5, 2.6, 2.7, 3.0, 3.1 | 1.9, 2.0, 2.1, 2.2, 2.3, 2.4 |
3ï¸â£ | older | N/A | Best of luck to you! | Please upgrade! |
NOTE: The 1.4 series will only receive critical security updates. See SECURITY.md.
ð§ Basic Usage
Global Configuration
You can turn on additional warnings.
OAuth2.configure do |config|
# Turn on a warning like:
# OAuth2::AccessToken.from_hash: `hash` contained more than one 'token' key
config.silence_extra_tokens_warning = false # default: true
# Set to true if you want to also show warnings about no tokens
config.silence_no_tokens_warning = false # default: true,
end
The "extra tokens" problem comes from ambiguity in the spec about which token is the right token.
Some OAuth 2.0 standards legitimately have multiple tokens.
You may need to subclass OAuth2::AccessToken
, or write your own custom alternative to it, and pass it in.
Specify your custom class with the access_token_class
option.
If you only need one token you can, as of v2.0.10,
specify the exact token name you want to extract via the OAuth2::AccessToken
using
the token_name
option.
You'll likely need to do some source diving. This gem has 100% test coverage for lines and branches, so the specs are a great place to look for ideas. If you have time and energy please contribute to the documentation!
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 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
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. See response_spec.rb if you need to study the hacks for older Rubies.
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
See response_spec.rb, or the oauth-xx/snaky_hash gem for more ideas.
What if I hate snakes and/or indifference?
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).
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.
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.
ð Security
See SECURITY.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 issues, or PRs, or use the gem and think about how it could be better.
We so if you make changes, remember to update it.
See CONTRIBUTING.md for more detailed instructions.
ð Release Instructions
See CONTRIBUTING.md.
Code Coverage
ðª Code of Conduct
Everyone interacting with this project's codebases, issue trackers,
chat rooms and mailing lists agrees to follow the .
ð Contributors
Made with contributors-img.
Also see GitLab Contributors: https://gitlab.com/oauth-xx/oauth2/-/graphs/main
âï¸ Star History
ð Versioning
This Library adheres to .
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.
ð Is "Platform Support" part of the public API?
Yes. But I'm obligated to include notes...
SemVer should, but doesn't explicitly, say that dropping support for specific Platforms is a breaking change to an API. It is obvious to many, but not all, and since the spec is silent, the bike shedding is endless.
dropping support for a platform is both obviously and objectively a breaking change
- Jordan Harband (@ljharb, maintainer of SemVer) in SemVer issue 716
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:
As a result of this policy, and the interpretive lens used by the maintainer, you can (and should) specify a dependency on these libraries using the Pessimistic Version Constraint with two digits of precision.
For example:
spec.add_dependency("oauth2", "~> 2.0")
See CHANGELOG.md for a list of releases.
ð License
The gem is available as open source under the terms of
the MIT License .
See LICENSE.txt for the official Copyright Notice.
© Copyright
-
Copyright (c) 2017â2025 Peter H. Boling, of
Galtzo.com
- Copyright (c) 2011-2013 Michael Bleigh and Intridea, Inc.
ð¤ One more thing
Having arrived at the bottom of the page, please endure a final supplication. The primary maintainer of this gem, Peter Boling, wants Ruby to be a great place for people to solve problems, big and small. Please consider supporting his efforts via the giant yellow link below, or one of smaller ones, depending on button size preference.
P.S. Use the gem => Discord for help
Top Related Projects
OmniAuth is a flexible authentication system utilizing Rack middleware.
Doorkeeper is an OAuth 2 provider for Ruby on Rails / Grape.
A Ruby wrapper for OAuth 2.0 protocol, including OIDC
Library for stubbing and setting expectations on HTTP requests in Ruby.
Simple Rails app configuration
A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot