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! |
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:
faraday
@ v0, v1, v2, HEAD ⏩️ lostisland/faradayjwt
@ v1, v2, v3, HEAD ⏩️ lostisland/faradaylogger
@ v1.2, v1.5, v1.7, HEAD ⏩️ jwt/ruby-jwtmulti_xml
@ v0.5, v0.6, v0.7, HEAD ⏩️ sferik/multi_xmlrack
@ v1.2, v1.6, v2, v3, HEAD ⏩️ rack/racksnaky_hash
@v2, HEAD ⏩️ oauth-xx/snaky_hashversion_gem
- @v1, HEAD ⏩️ oauth-xx/version_gemThe 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:
hashie
@ v0, v1, v2, v3, v4, v5, HEAD ⏩️ hashie/hashie* 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! |
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:
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 🎖️ | |
... 💖 |
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
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.
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.
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
For more see SECURITY.md.
application/vdn.api+json
, application/vnd.collection+json
, application/hal+json
, application/problem+json
OAuth2::Client#get_token
:
:access_token_class
(AccessToken
); user specified class to use for all calls to get_token
OAuth2::AccessToken#initialize
:
:expires_latency
(nil
); number of seconds by which AccessToken validity will be reduced to offset latencyresponse.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.snaky: false
option.:auth_scheme
is now :basic_auth
(instead of :request_body
)
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 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.
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
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"
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
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)
As of v2.0.11, if you need to serialize the parsed result, you can!
There are two ways to do this, and the second option recommended.
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
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)
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.
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).
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.
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.
See CONTRIBUTING.md.
See SECURITY.md.
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.
Everyone interacting in this project’s codebases, issue trackers,
chat rooms and mailing lists is expected to follow the .
Made with contributors-img.
Also see GitLab Contributors: https://gitlab.com/oauth-xx/oauth2/-/graphs/main
</a>
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.
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
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 list of releases.
The gem is available as open source under the terms of
the MIT License .
See LICENSE.txt for the official Copyright Notice.
You made it to the bottom of the page, so perhaps you’ll indulge me for another 20 seconds. I maintain many dozens of gems, including this one, because I want Ruby to be a great place for people to solve problems, big and small. Please consider supporting my efforts via the giant yellow link below, or one of the others at the head of this README.