Home

Awesome

<p align="center"> <a href="http://oauth.net/2/" target="_blank" rel="noopener"> <img src="https://github.com/oauth-xx/oauth2/raw/main/docs/images/logo/oauth2-logo-124px.png?raw=true" alt="OAuth 2.0 Logo by Chris Messina, CC BY-SA 3.0"> </a> <a href="https://www.ruby-lang.org/" target="_blank" rel="noopener"> <img width="124px" src="https://github.com/oauth-xx/oauth2/raw/main/docs/images/logo/ruby-logo-198px.svg?raw=true" alt="Yukihiro Matsumoto, Ruby Visual Identity Team, CC BY-SA 2.5"> </a> </p>

What

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.


Release Documentation

Version 2.0.x

<details> <summary>2.0.x Readmes</summary>
VersionRelease DateReadme
2.0.102022-09-27https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.10/README.md
2.0.92022-09-16https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.9/README.md
2.0.82022-09-01https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.8/README.md
2.0.72022-08-22https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.7/README.md
2.0.62022-07-13https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.6/README.md
2.0.52022-07-07https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.5/README.md
2.0.42022-07-01https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.4/README.md
2.0.32022-06-28https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.3/README.md
2.0.22022-06-24https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.2/README.md
2.0.12022-06-22https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.1/README.md
2.0.02022-06-21https://gitlab.com/oauth-xx/oauth2/-/blob/v2.0.0/README.md
</details>

Older Releases

<details> <summary>1.4.x Readmes</summary>
VersionRelease DateReadme
1.4.11Sep 16, 2022https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.11/README.md
1.4.10Jul 1, 2022https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.10/README.md
1.4.9Feb 20, 2022https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.9/README.md
1.4.8Feb 18, 2022https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.8/README.md
1.4.7Mar 19, 2021https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.7/README.md
1.4.6Mar 19, 2021https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.6/README.md
1.4.5Mar 18, 2021https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.5/README.md
1.4.4Feb 12, 2020https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.4/README.md
1.4.3Jan 29, 2020https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.3/README.md
1.4.2Oct 1, 2019https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.2/README.md
1.4.1Oct 13, 2018https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.1/README.md
1.4.0Jun 9, 2017https://gitlab.com/oauth-xx/oauth2/-/blob/v1.4.0/README.md
</details> <details> <summary>1.3.x Readmes</summary>
VersionRelease DateReadme
1.3.1Mar 3, 2017https://gitlab.com/oauth-xx/oauth2/-/blob/v1.3.1/README.md
1.3.0Dec 27, 2016https://gitlab.com/oauth-xx/oauth2/-/blob/v1.3.0/README.md
</details> <details> <summary>&le;= 1.2.x Readmes (2016 and before)</summary>
VersionRelease DateReadme
1.2.0Jun 30, 2016https://gitlab.com/oauth-xx/oauth2/-/blob/v1.2.0/README.md
1.1.0Jan 30, 2016https://gitlab.com/oauth-xx/oauth2/-/blob/v1.1.0/README.md
1.0.0May 23, 2014https://gitlab.com/oauth-xx/oauth2/-/blob/v1.0.0/README.md
< 1.0.0Find herehttps://gitlab.com/oauth-xx/oauth2/-/tags
</details>

Status

<!-- Numbering rows and badges in each row as a visual "database" lookup, as the table is extremely dense, and it can be very difficult to find anything Putting one on each row here, to document the emoji that should be used, and for ease of copy/paste. row #s: 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ badge #s: ⛳️ 🖇 🏘 🚎 🖐 🧮 📗 appended indicators: ♻️ - URL needs to be updated from SASS integration. Find / Replace is insufficient. -->
Projectbundle add oauth2
1️⃣name, license, docsRubyGems.org License: MIT FOSSA RubyDoc.info SemVer 2.0.0 Keep-A-Changelog 1.0.0
2️⃣version & activityGem Version Total Downloads Download Rank Source Code
3️⃣maintanence & lintingMaintainability Helpers Depfu Contributors Style
4️⃣testingSupported Heads Unofficial Support MacOS Windows
5️⃣coverage & securityCodeClimate CodeCov Coveralls Security Policy CodeQL Code Coverage
6️⃣resourcesDiscussion Get help on Codementor Chat Blog Blog
7️⃣spread 💖Liberapay Patrons Sponsor Me Tweet @ Peter 🌏 👼 💻
<!-- The link tokens in the following sections should be kept ordered by the row and badge numbering scheme --> <!-- 1️⃣ name, license, docs --> <!-- 2️⃣ version & activity --> <!-- 3️⃣ maintenance & linting --> <!-- 4️⃣ testing --> <!-- 5️⃣ coverage & security --> <!-- 6️⃣ resources --> <!-- 7️⃣ spread 💖 --> <!-- Maintainer Contact Links -->

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

OAuth2 for Enterprise

Available as part of the Tidelift Subscription.

The maintainers of OAuth2 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?

Compatibility

Targeted ruby compatibility is non-EOL versions of Ruby, currently 2.7, 3.0 and 3.1. Compatibility is further distinguished by supported and unsupported versions of Ruby. Ruby is limited to 2.2+ for 2.x releases. See 1-4-stable branch for older rubies.

<details> <summary>Ruby Engine Compatibility Policy</summary>

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.

</details> <details> <summary>Ruby Version Compatibility Policy</summary>

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.

</details>
Ruby OAuth2 VersionMaintenance BranchSupported OfficiallySupported UnofficiallySupported Incidentally
1️⃣2.0.xmain2.7, 3.0, 3.12.5, 2.62.2, 2.3, 2.4
2️⃣1.4.x1-4-stable2.5, 2.6, 2.7, 3.0, 3.12.1, 2.2, 2.3, 2.41.9, 2.0
3️⃣olderN/ABest of luck to you!Please upgrade!

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

Usage Examples

Global Configuration

If you started seeing this warning, but everything it working fine, you can now silence it.

OAuth2::AccessToken.from_hash: `hash` contained more than one 'token' key
OAuth2.configure do |config|
  config.silence_extra_tokens_warning = true # default: false
end

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        # => OAuth2::SnakyHash (subclass of Hashie::Mash::Rash, from `rash_alt` gem)

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)
<details> <summary>Debugging</summary>

Set an environment variable, however you would normally do that.

# 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')
)
</details>

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 OAuth2::SnakyHash 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.

Versioning

This library aims to adhere 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.

As a result of this policy, you can (and should) specify a dependency on this gem using the Pessimistic Version Constraint with two digits of precision.

For example:

spec.add_dependency 'oauth2', '~> 2.0'

License

License: MIT

FOSSA Status

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then 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 rubygems.org.

Contributing

See CONTRIBUTING.md

Contributors

Contributors

Made with contributors-img.

Code of Conduct

Everyone interacting in the OAuth2 project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.