OAuth 2.0 and Library
What the libraries do?
How can we use the libraries?
What is OAuth 2.0?
● Standard to authenticate the client application so that it can access to
protected resource.
● The user doesn't have to provide own user id and password.
● RFC6749
OAuth Flow (simple version)
Client App
Resource Svr
Auth Svr
Start
(1) Authorization Client
Redirect and authenticate
Respond Code
(2) Request Token
Respond Token
(3) Request Resource
redirect_uri
client_id
scope
response_type
grant_type
client_id
scope
code
code
state
access_token
token_type
expires_in
refresh_token
example_parameter
OAuth Flow (simple version
Client App
Resource Svr
Auth Svr
Start
(1) Authenticate Client
Redirect and authenticate
Respond Code
(2) Request Token
Respond Token
(3) Request Resource
3 endpoint URLs for
configuration
PHP Library: thephpleague/oauth2-client
https://github.com/thephpleague/oauth2-client
$provider = new LeagueOAuth2ClientProviderGenericProvider([
'clientId' => 'demoapp', // The client ID assigned to you by the provider
'clientSecret' => 'demopass', // The client password assigned to you by the provider
'redirectUri' => 'http://example.com/your-redirect-url/',
'urlAuthorize' => 'http://brentertainment.com/oauth2/lockdin/authorize',
'urlAccessToken' => 'http://brentertainment.com/oauth2/lockdin/token',
'urlResourceOwnerDetails' => 'http://brentertainment.com/oauth2/lockdin/resource'
]);
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {
if (isset($_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
}
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo 'Access Token: ' . $accessToken->getToken() . "<br>";
echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
Let's view the sample code.
PHP Library: thephpleague/oauth2-client
$provider = new LeagueOAuth2ClientProviderGenericProvider([
'clientId' => 'demoapp', // The client ID assigned to you by the provider
'clientSecret' => 'demopass', // The client password assigned to you by the provider
'redirectUri' => 'http://example.com/your-redirect-url/',
'urlAuthorize' => 'http://brentertainment.com/oauth2/lockdin/authorize',
'urlAccessToken' => 'http://brentertainment.com/oauth2/lockdin/token',
'urlResourceOwnerDetails' => 'http://brentertainment.com/oauth2/lockdin/resource'
]);
3 URLs for auth and resource server.
PHP Library: thephpleague/oauth2-client
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
Conditional with parameters.
(1) first step
Authorization URL
Redirection to authorization URL, such as
Twitter login view.
PHP Library: thephpleague/oauth2-client
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !==
$_SESSION['oauth2state'])) {
if (isset($_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
}
exit('Invalid state');
Process when the user came back from authorization.
Handles irregular pattern
PHP Library: thephpleague/oauth2-client
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo 'Access Token: ' . $accessToken->getToken() . "<br>";
echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to PsrHttpMessageRequestInterface.
$request = $provider->getAuthenticatedRequest(
'GET',
'http://brentertainment.com/oauth2/lockdin/resource',
$accessToken
);
} catch (LeagueOAuth2ClientProviderExceptionIdentityProviderException$e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
(2) Get Access token
(3) Get resource information
PHP Library: thephpleague/oauth2-client
It enables us to develop application with user data based on old PHP website.
Ruby Library: omniauth/omniauth
https://github.com/omniauth/omniauth
omniauth-twitter, omniauth-facebook, omniauth-google are often used when
developing Twitter/Google/Facebook Authorization in Rails.
The main differences in omniauth-twitter, omniauth-facebook, omniauth-google are
the 3 URLs.
There are many libraries for many auth
servers with omniauth in GitHub.
The difference is 3 URLs and most
complicated part is handled by omniauth, so
implementation in each library such as
omniauth-twitter is really simple.
Ruby Library: omniauth/omniauth
The main component omniauth-google-oauth2 is google_oauth2.rb, 227 lines.
Ruby Library: omniauth/omniauth
The main component of omniauth-facebook is facebook.rb, 180 lines.
Library to develop server: Doorkeeper
https://github.com/doorkeeper-gem/doorkeeper
It is used with Rails and it collaborates with Devise well.
Library to develop server: Doorkeeper
● For manager
○ With manager account, we can configure client applications.
○ We can register multiple managers. Devise can be used for managing manager.
● For user
○ All function for user are prepared.
● What the developer do
○ (1) create user authorization page
■ Devise can generate those code.
○ (3) create endpoint to return resource information
Library to develop server: Doorkeeper
Endpoint to return resource information.
The library handles most part. The main code of the endpoint can be written as
follows. Simple.
module Api
class V1::ApiController < ::ApplicationController
def current_resource_owner
Member.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
end
end
end
module Api
class V1::CredentialsController < V1::ApiController
before_action :doorkeeper_authorize!
def me
render json: { member: current_resource_owner }
end
end
end
Reference
● OAuth 2.0 structure and authorization https://murashun.jp/blog/20150920-01.html
● OAuth 2.0 client in Java https://www.ibm.com/developerworks/jp/security/library/se-oauthjavapt3/index.html
● OAuth authorization with Rails + devise + omniauth + doorkeeper
https://qiita.com/moehiko/items/300dcfa4d8f70660bcd1

OAuth 2.0 and Library

  • 1.
    OAuth 2.0 andLibrary What the libraries do? How can we use the libraries?
  • 2.
    What is OAuth2.0? ● Standard to authenticate the client application so that it can access to protected resource. ● The user doesn't have to provide own user id and password. ● RFC6749
  • 3.
    OAuth Flow (simpleversion) Client App Resource Svr Auth Svr Start (1) Authorization Client Redirect and authenticate Respond Code (2) Request Token Respond Token (3) Request Resource redirect_uri client_id scope response_type grant_type client_id scope code code state access_token token_type expires_in refresh_token example_parameter
  • 4.
    OAuth Flow (simpleversion Client App Resource Svr Auth Svr Start (1) Authenticate Client Redirect and authenticate Respond Code (2) Request Token Respond Token (3) Request Resource 3 endpoint URLs for configuration
  • 5.
    PHP Library: thephpleague/oauth2-client https://github.com/thephpleague/oauth2-client $provider= new LeagueOAuth2ClientProviderGenericProvider([ 'clientId' => 'demoapp', // The client ID assigned to you by the provider 'clientSecret' => 'demopass', // The client password assigned to you by the provider 'redirectUri' => 'http://example.com/your-redirect-url/', 'urlAuthorize' => 'http://brentertainment.com/oauth2/lockdin/authorize', 'urlAccessToken' => 'http://brentertainment.com/oauth2/lockdin/token', 'urlResourceOwnerDetails' => 'http://brentertainment.com/oauth2/lockdin/resource' ]); // If we don't have an authorization code then get one if (!isset($_GET['code'])) { // Fetch the authorization URL from the provider; this returns the // urlAuthorize option and generates and applies any necessary parameters // (e.g. state). $authorizationUrl = $provider->getAuthorizationUrl(); // Get the state generated for you and store it to the session. $_SESSION['oauth2state'] = $provider->getState(); // Redirect the user to the authorization URL. header('Location: ' . $authorizationUrl); exit; // Check given state against previously stored one to mitigate CSRF attack } elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) { if (isset($_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); } exit('Invalid state'); } else { try { // Try to get an access token using the authorization code grant. $accessToken = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // We have an access token, which we may use in authenticated // requests against the service provider's API. echo 'Access Token: ' . $accessToken->getToken() . "<br>"; echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>"; echo 'Expired in: ' . $accessToken->getExpires() . "<br>"; echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>"; Let's view the sample code.
  • 6.
    PHP Library: thephpleague/oauth2-client $provider= new LeagueOAuth2ClientProviderGenericProvider([ 'clientId' => 'demoapp', // The client ID assigned to you by the provider 'clientSecret' => 'demopass', // The client password assigned to you by the provider 'redirectUri' => 'http://example.com/your-redirect-url/', 'urlAuthorize' => 'http://brentertainment.com/oauth2/lockdin/authorize', 'urlAccessToken' => 'http://brentertainment.com/oauth2/lockdin/token', 'urlResourceOwnerDetails' => 'http://brentertainment.com/oauth2/lockdin/resource' ]); 3 URLs for auth and resource server.
  • 7.
    PHP Library: thephpleague/oauth2-client //If we don't have an authorization code then get one if (!isset($_GET['code'])) { // Fetch the authorization URL from the provider; this returns the // urlAuthorize option and generates and applies any necessary parameters // (e.g. state). $authorizationUrl = $provider->getAuthorizationUrl(); // Get the state generated for you and store it to the session. $_SESSION['oauth2state'] = $provider->getState(); // Redirect the user to the authorization URL. header('Location: ' . $authorizationUrl); exit; Conditional with parameters. (1) first step Authorization URL Redirection to authorization URL, such as Twitter login view.
  • 8.
    PHP Library: thephpleague/oauth2-client //Check given state against previously stored one to mitigate CSRF attack } elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) { if (isset($_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); } exit('Invalid state'); Process when the user came back from authorization. Handles irregular pattern
  • 9.
    PHP Library: thephpleague/oauth2-client }else { try { // Try to get an access token using the authorization code grant. $accessToken = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // We have an access token, which we may use in authenticated // requests against the service provider's API. echo 'Access Token: ' . $accessToken->getToken() . "<br>"; echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>"; echo 'Expired in: ' . $accessToken->getExpires() . "<br>"; echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>"; // Using the access token, we may look up details about the // resource owner. $resourceOwner = $provider->getResourceOwner($accessToken); var_export($resourceOwner->toArray()); // The provider provides a way to get an authenticated API request for // the service, using the access token; it returns an object conforming // to PsrHttpMessageRequestInterface. $request = $provider->getAuthenticatedRequest( 'GET', 'http://brentertainment.com/oauth2/lockdin/resource', $accessToken ); } catch (LeagueOAuth2ClientProviderExceptionIdentityProviderException$e) { // Failed to get the access token or user details. exit($e->getMessage()); } } (2) Get Access token (3) Get resource information
  • 10.
    PHP Library: thephpleague/oauth2-client Itenables us to develop application with user data based on old PHP website.
  • 11.
    Ruby Library: omniauth/omniauth https://github.com/omniauth/omniauth omniauth-twitter,omniauth-facebook, omniauth-google are often used when developing Twitter/Google/Facebook Authorization in Rails. The main differences in omniauth-twitter, omniauth-facebook, omniauth-google are the 3 URLs. There are many libraries for many auth servers with omniauth in GitHub. The difference is 3 URLs and most complicated part is handled by omniauth, so implementation in each library such as omniauth-twitter is really simple.
  • 12.
    Ruby Library: omniauth/omniauth Themain component omniauth-google-oauth2 is google_oauth2.rb, 227 lines.
  • 13.
    Ruby Library: omniauth/omniauth Themain component of omniauth-facebook is facebook.rb, 180 lines.
  • 14.
    Library to developserver: Doorkeeper https://github.com/doorkeeper-gem/doorkeeper It is used with Rails and it collaborates with Devise well.
  • 15.
    Library to developserver: Doorkeeper ● For manager ○ With manager account, we can configure client applications. ○ We can register multiple managers. Devise can be used for managing manager. ● For user ○ All function for user are prepared. ● What the developer do ○ (1) create user authorization page ■ Devise can generate those code. ○ (3) create endpoint to return resource information
  • 16.
    Library to developserver: Doorkeeper Endpoint to return resource information. The library handles most part. The main code of the endpoint can be written as follows. Simple. module Api class V1::ApiController < ::ApplicationController def current_resource_owner Member.find(doorkeeper_token.resource_owner_id) if doorkeeper_token end end end module Api class V1::CredentialsController < V1::ApiController before_action :doorkeeper_authorize! def me render json: { member: current_resource_owner } end end end
  • 17.
    Reference ● OAuth 2.0structure and authorization https://murashun.jp/blog/20150920-01.html ● OAuth 2.0 client in Java https://www.ibm.com/developerworks/jp/security/library/se-oauthjavapt3/index.html ● OAuth authorization with Rails + devise + omniauth + doorkeeper https://qiita.com/moehiko/items/300dcfa4d8f70660bcd1