SlideShare a Scribd company logo
1 of 18
Download to read offline
OAuth 2.0とライブラリ
ライブラリはなにをやっているのか、
どうやって使うのか
OAuth とは
● 保護されたサーバー・リソースへのアクセス権を、クライアントアプリケーションが取
得できるように認可するためのオープン・スタンダードです。
● ユーザはクライアントに自分のユーザ名・パスワードを共有する必要がありませ
ん。
● RFC6749
OAuth で情報を取得するまで (簡易版)
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 で情報を取得するまで (簡易版)
Client App
Resource Svr
Auth Svr
Start
(1) Authorization Client
Redirect and authenticate
Respond Code
(2) Request Token
Respond Token
(3) Request Resource
設定には
3つのURLが必要
OAuth で情報を取得するまで (簡易版)
Client App
Resource Svr
Auth Svr
Start
(1) Authorization Client
Redirect and authenticate
Respond Code
(2) Request Token
Respond Token
(3) Request Resource
クライアントライブラリはここで使う
PHPのライブラリ: 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>";
サンプルコードを上から見ていきましょう。
PHPのライブラリ: 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つのURL
PHPのライブラリ: 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;
パラメータで分岐しながら処理をする。
(1) 最初のステップ
認証URL
認証URLへリダイレクト
リダイレクト先は Twitter などの認証画面
PHPのライブラリ: 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');
認可から帰ってきたときの処理。
まずはイレギュラーパターンの処理。
PHPのライブラリ: 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) アクセストークンの取得
(3) リソース情報の取得
PHPのライブラリ: thephpleague/oauth2-client
基本がこれだけなので、既存のPHPのウェブサイトでもうまく組み合わせればユーザ
データを使ったアプリケーション開発が可能。
Ruby のライブラリ: omniauth/omniauth
https://github.com/omniauth/omniauth
Rails で Twitter/Google/Facebook 認証 を行う場合には、 よく omniauth-twitter,
omniauth-facebook, omniauth-google が使われる。
omniauth-twitter, omniauth-facebook, omniauth-google の違いは3つのURL。
GitHub では omniauth を使った非常にたくさんのサーバについてのライブラリが公開さ
れている。
設定が異なるのは3つのURLになるので
各サーバのライブラリは非常にシンプル。
基本は omniauth 本体が行うので
3つのURLを設定するのみ。
Ruby のライブラリ: omniauth/omniauth
omniauth-google-oauth2 の本体は google_oauth2.rb で227行。
Ruby のライブラリ: omniauth/omniauth
データを整形するコードがあったりする omniauth-facebook の本体は facebook.rb で
わずか180行。
サーバのためのライブラリ: Doorkeeper
https://github.com/doorkeeper-gem/doorkeeper
Rails と組み合わせて使うもので、 Devise とうまく連携できるようになっている。
サーバのためのライブラリ: Doorkeeper
● 管理者用
○ 管理者アカウントを使って、クライアントアプリケーションを登録・編集可能。
○ 管理者は複数登録できる。 Devise が使える。
● ユーザ用
○ ユーザが使うための機能はひととおり揃っている。
● 開発者がやること
○ (1) ユーザ認証画面の作成
■ Devise を使えばよい。
○ (3) リソースデータを返すためのエンドポイント作成
サーバのためのライブラリ: Doorkeeper
リソースデータを返すエンドポイント
ライブラリがほとんど処理してくれる。エンドポイントのコードは下のように作る。
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
参考
● OAuth 2.0 の仕組みと認証方法 https://murashun.jp/blog/20150920-01.html
● Java プログラミングで実装する OAuth 2.0 クライアント
https://www.ibm.com/developerworks/jp/security/library/se-oauthjavapt3/index.html
● Rails + devise + omniauth + doorkeeperでoauth認証を行う
https://qiita.com/moehiko/items/300dcfa4d8f70660bcd1

More Related Content

Similar to OAuth 2.0 と ライブラリ

OpenStack Study#9 JOSUG
OpenStack Study#9 JOSUGOpenStack Study#9 JOSUG
OpenStack Study#9 JOSUGHideki Saito
 
「金融API向けOAuth」にみるOAuthプロファイリングの実際 #secjaws #finsecjaws01 #oauth #oidc #api
「金融API向けOAuth」にみるOAuthプロファイリングの実際 #secjaws #finsecjaws01 #oauth #oidc #api「金融API向けOAuth」にみるOAuthプロファイリングの実際 #secjaws #finsecjaws01 #oauth #oidc #api
「金融API向けOAuth」にみるOAuthプロファイリングの実際 #secjaws #finsecjaws01 #oauth #oidc #apiTatsuo Kudo
 
The Latest Specs of OpenID Connect at #idcon 9
The Latest Specs of OpenID Connect at #idcon 9The Latest Specs of OpenID Connect at #idcon 9
The Latest Specs of OpenID Connect at #idcon 9Ryo Ito
 
Financial-grade API Hands-on with Authlete
Financial-grade API Hands-on with AuthleteFinancial-grade API Hands-on with Authlete
Financial-grade API Hands-on with AuthleteTatsuo Kudo
 
FAPI (Financial-grade API) and CIBA (Client Initiated Backchannel Authenticat...
FAPI (Financial-grade API) and CIBA (Client Initiated Backchannel Authenticat...FAPI (Financial-grade API) and CIBA (Client Initiated Backchannel Authenticat...
FAPI (Financial-grade API) and CIBA (Client Initiated Backchannel Authenticat...Tatsuo Kudo
 
API Gateway - ヘッダー/クエリー変換、認証・認可機能詳細
API Gateway - ヘッダー/クエリー変換、認証・認可機能詳細API Gateway - ヘッダー/クエリー変換、認証・認可機能詳細
API Gateway - ヘッダー/クエリー変換、認証・認可機能詳細オラクルエンジニア通信
 
勉強会force#4 Chatter Integration
勉強会force#4 Chatter Integration勉強会force#4 Chatter Integration
勉強会force#4 Chatter IntegrationKazuki Nakajima
 
なんとなくOAuth怖いって思ってるやつちょっと来い
なんとなくOAuth怖いって思ってるやつちょっと来いなんとなくOAuth怖いって思ってるやつちょっと来い
なんとなくOAuth怖いって思ってるやつちょっと来いRyo Ito
 
LINEログインの最新アップデートとアプリ連携ウォークスルー
LINEログインの最新アップデートとアプリ連携ウォークスルーLINEログインの最新アップデートとアプリ連携ウォークスルー
LINEログインの最新アップデートとアプリ連携ウォークスルーNaohiro Fujie
 
UserManagedAccess_idcon13
UserManagedAccess_idcon13UserManagedAccess_idcon13
UserManagedAccess_idcon13Ryo Ito
 
ログ管理のベストプラクティス
ログ管理のベストプラクティスログ管理のベストプラクティス
ログ管理のベストプラクティスAkihiro Kuwano
 
20120201 aws meister-reloaded-iam-and-billing-public
20120201 aws meister-reloaded-iam-and-billing-public20120201 aws meister-reloaded-iam-and-billing-public
20120201 aws meister-reloaded-iam-and-billing-publicAmazon Web Services Japan
 
Idcon11 implicit demo
Idcon11 implicit demoIdcon11 implicit demo
Idcon11 implicit demoRyo Ito
 
API提供におけるOAuthの役割 #apijp
API提供におけるOAuthの役割 #apijpAPI提供におけるOAuthの役割 #apijp
API提供におけるOAuthの役割 #apijpTatsuo Kudo
 
OAuth 2.0の概要とセキュリティ
OAuth 2.0の概要とセキュリティOAuth 2.0の概要とセキュリティ
OAuth 2.0の概要とセキュリティHiroshi Hayakawa
 

Similar to OAuth 2.0 と ライブラリ (20)

OpenStack Study#9 JOSUG
OpenStack Study#9 JOSUGOpenStack Study#9 JOSUG
OpenStack Study#9 JOSUG
 
「金融API向けOAuth」にみるOAuthプロファイリングの実際 #secjaws #finsecjaws01 #oauth #oidc #api
「金融API向けOAuth」にみるOAuthプロファイリングの実際 #secjaws #finsecjaws01 #oauth #oidc #api「金融API向けOAuth」にみるOAuthプロファイリングの実際 #secjaws #finsecjaws01 #oauth #oidc #api
「金融API向けOAuth」にみるOAuthプロファイリングの実際 #secjaws #finsecjaws01 #oauth #oidc #api
 
The Latest Specs of OpenID Connect at #idcon 9
The Latest Specs of OpenID Connect at #idcon 9The Latest Specs of OpenID Connect at #idcon 9
The Latest Specs of OpenID Connect at #idcon 9
 
Financial-grade API Hands-on with Authlete
Financial-grade API Hands-on with AuthleteFinancial-grade API Hands-on with Authlete
Financial-grade API Hands-on with Authlete
 
PFI Seminar 2012/02/24
PFI Seminar 2012/02/24PFI Seminar 2012/02/24
PFI Seminar 2012/02/24
 
20111203
2011120320111203
20111203
 
FAPI (Financial-grade API) and CIBA (Client Initiated Backchannel Authenticat...
FAPI (Financial-grade API) and CIBA (Client Initiated Backchannel Authenticat...FAPI (Financial-grade API) and CIBA (Client Initiated Backchannel Authenticat...
FAPI (Financial-grade API) and CIBA (Client Initiated Backchannel Authenticat...
 
OpenStack API
OpenStack APIOpenStack API
OpenStack API
 
API Gateway - ヘッダー/クエリー変換、認証・認可機能詳細
API Gateway - ヘッダー/クエリー変換、認証・認可機能詳細API Gateway - ヘッダー/クエリー変換、認証・認可機能詳細
API Gateway - ヘッダー/クエリー変換、認証・認可機能詳細
 
Tottoruby 20110903
Tottoruby 20110903Tottoruby 20110903
Tottoruby 20110903
 
勉強会force#4 Chatter Integration
勉強会force#4 Chatter Integration勉強会force#4 Chatter Integration
勉強会force#4 Chatter Integration
 
なんとなくOAuth怖いって思ってるやつちょっと来い
なんとなくOAuth怖いって思ってるやつちょっと来いなんとなくOAuth怖いって思ってるやつちょっと来い
なんとなくOAuth怖いって思ってるやつちょっと来い
 
LINEログインの最新アップデートとアプリ連携ウォークスルー
LINEログインの最新アップデートとアプリ連携ウォークスルーLINEログインの最新アップデートとアプリ連携ウォークスルー
LINEログインの最新アップデートとアプリ連携ウォークスルー
 
UserManagedAccess_idcon13
UserManagedAccess_idcon13UserManagedAccess_idcon13
UserManagedAccess_idcon13
 
ログ管理のベストプラクティス
ログ管理のベストプラクティスログ管理のベストプラクティス
ログ管理のベストプラクティス
 
Using Dancer
Using DancerUsing Dancer
Using Dancer
 
20120201 aws meister-reloaded-iam-and-billing-public
20120201 aws meister-reloaded-iam-and-billing-public20120201 aws meister-reloaded-iam-and-billing-public
20120201 aws meister-reloaded-iam-and-billing-public
 
Idcon11 implicit demo
Idcon11 implicit demoIdcon11 implicit demo
Idcon11 implicit demo
 
API提供におけるOAuthの役割 #apijp
API提供におけるOAuthの役割 #apijpAPI提供におけるOAuthの役割 #apijp
API提供におけるOAuthの役割 #apijp
 
OAuth 2.0の概要とセキュリティ
OAuth 2.0の概要とセキュリティOAuth 2.0の概要とセキュリティ
OAuth 2.0の概要とセキュリティ
 

Recently uploaded

業務で生成AIを活用したい人のための生成AI入門講座(社外公開版) 2024年4月作成
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版) 2024年4月作成業務で生成AIを活用したい人のための生成AI入門講座(社外公開版) 2024年4月作成
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版) 2024年4月作成Hiroshi Tomioka
 
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?akihisamiyanaga1
 
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineerYuki Kikuchi
 
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)UEHARA, Tetsutaro
 
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdfAWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdfFumieNakayama
 
TataPixel: 畳の異方性を利用した切り替え可能なディスプレイの提案
TataPixel: 畳の異方性を利用した切り替え可能なディスプレイの提案TataPixel: 畳の異方性を利用した切り替え可能なディスプレイの提案
TataPixel: 畳の異方性を利用した切り替え可能なディスプレイの提案sugiuralab
 
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdfクラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdfFumieNakayama
 
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)Hiroki Ichikura
 
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察 ~Text-to-MusicとText-To-ImageかつImage-to-Music...
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察  ~Text-to-MusicとText-To-ImageかつImage-to-Music...モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察  ~Text-to-MusicとText-To-ImageかつImage-to-Music...
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察 ~Text-to-MusicとText-To-ImageかつImage-to-Music...博三 太田
 

Recently uploaded (9)

業務で生成AIを活用したい人のための生成AI入門講座(社外公開版) 2024年4月作成
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版) 2024年4月作成業務で生成AIを活用したい人のための生成AI入門講座(社外公開版) 2024年4月作成
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版) 2024年4月作成
 
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
 
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
 
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
 
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdfAWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
 
TataPixel: 畳の異方性を利用した切り替え可能なディスプレイの提案
TataPixel: 畳の異方性を利用した切り替え可能なディスプレイの提案TataPixel: 畳の異方性を利用した切り替え可能なディスプレイの提案
TataPixel: 畳の異方性を利用した切り替え可能なディスプレイの提案
 
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdfクラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
 
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
 
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察 ~Text-to-MusicとText-To-ImageかつImage-to-Music...
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察  ~Text-to-MusicとText-To-ImageかつImage-to-Music...モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察  ~Text-to-MusicとText-To-ImageかつImage-to-Music...
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察 ~Text-to-MusicとText-To-ImageかつImage-to-Music...
 

OAuth 2.0 と ライブラリ

  • 3. OAuth で情報を取得するまで (簡易版) 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 で情報を取得するまで (簡易版) Client App Resource Svr Auth Svr Start (1) Authorization Client Redirect and authenticate Respond Code (2) Request Token Respond Token (3) Request Resource 設定には 3つのURLが必要
  • 5. OAuth で情報を取得するまで (簡易版) Client App Resource Svr Auth Svr Start (1) Authorization Client Redirect and authenticate Respond Code (2) Request Token Respond Token (3) Request Resource クライアントライブラリはここで使う
  • 6. PHPのライブラリ: 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>"; サンプルコードを上から見ていきましょう。
  • 7. PHPのライブラリ: 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つのURL
  • 8. PHPのライブラリ: 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; パラメータで分岐しながら処理をする。 (1) 最初のステップ 認証URL 認証URLへリダイレクト リダイレクト先は Twitter などの認証画面
  • 9. PHPのライブラリ: 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'); 認可から帰ってきたときの処理。 まずはイレギュラーパターンの処理。
  • 10. PHPのライブラリ: 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) アクセストークンの取得 (3) リソース情報の取得
  • 12. Ruby のライブラリ: omniauth/omniauth https://github.com/omniauth/omniauth Rails で Twitter/Google/Facebook 認証 を行う場合には、 よく omniauth-twitter, omniauth-facebook, omniauth-google が使われる。 omniauth-twitter, omniauth-facebook, omniauth-google の違いは3つのURL。 GitHub では omniauth を使った非常にたくさんのサーバについてのライブラリが公開さ れている。 設定が異なるのは3つのURLになるので 各サーバのライブラリは非常にシンプル。 基本は omniauth 本体が行うので 3つのURLを設定するのみ。
  • 13. Ruby のライブラリ: omniauth/omniauth omniauth-google-oauth2 の本体は google_oauth2.rb で227行。
  • 14. Ruby のライブラリ: omniauth/omniauth データを整形するコードがあったりする omniauth-facebook の本体は facebook.rb で わずか180行。
  • 16. サーバのためのライブラリ: Doorkeeper ● 管理者用 ○ 管理者アカウントを使って、クライアントアプリケーションを登録・編集可能。 ○ 管理者は複数登録できる。 Devise が使える。 ● ユーザ用 ○ ユーザが使うための機能はひととおり揃っている。 ● 開発者がやること ○ (1) ユーザ認証画面の作成 ■ Devise を使えばよい。 ○ (3) リソースデータを返すためのエンドポイント作成
  • 17. サーバのためのライブラリ: Doorkeeper リソースデータを返すエンドポイント ライブラリがほとんど処理してくれる。エンドポイントのコードは下のように作る。 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
  • 18. 参考 ● OAuth 2.0 の仕組みと認証方法 https://murashun.jp/blog/20150920-01.html ● Java プログラミングで実装する OAuth 2.0 クライアント https://www.ibm.com/developerworks/jp/security/library/se-oauthjavapt3/index.html ● Rails + devise + omniauth + doorkeeperでoauth認証を行う https://qiita.com/moehiko/items/300dcfa4d8f70660bcd1