oauth2 - A Ruby wrapper for the OAuth 2.0 specification.

 gem install oauth2

Basics of OAuth2 is well explained here: Oauth2 basics

Creating OAuth2::Client instance

require 'oauth2'
client = OAuth2::Client.new('client_id', 'client_secret', :site => 'https://example.org')

OAuth2 provides four authentication grant types :

  • Authorization Code Grant
  • Implicit Grant
  • Resource Owner Password Credentials Grant
  • Client Credentials Grant

In UN project, we have used Resource Owner Password Credentials Grant type

token = client.password.get_token('username', 'password')

In case if Credentials are not correct, OAuth2::Error will be raised.

With correct credentials, it gives OAuth2::AccessToken instance which can be used to request User specific info from external API.

OAuth2::AccessToken instance generally contains:

 { "access_token"  : "...",
  "token_type"    : "...",
  "expires_in"    : "...",
  "refresh_token" : "...",
}

where

  • access_token - token as assigned by the authorization server.
  • token_type - type of token assigned by the authorization server.
  • expires_in - a number of seconds after which the access token expires, and is no longer valid. Expiration of access tokens is optional.
  • refresh_token - refresh token in case the access token can expire. The refresh token is used to obtain a new access token once the one returned in this response is no longer valid.
 token.get('http://example.org'/api/user_resource?format=json') 

This will give OAuth2::Response instance which contains User info in JSON form.

Why to use OAuth2?

OAuth 2.0 promises to simplify stuff in a number of ways:

  1. SSL is required for all the communications required to generate the token. This is a huge decrease in complexity because those complex signatures are no longer required.

  2. Signatures are not required for the actual API calls once the token has been generated -- SSL is also strongly recommended here.

  3. Once the token was generated, OAuth 1.0 required that the client send two security tokens on every API call, and use both to generate the signature. OAuth 2.0 has only one security token, and no signature is required.