yii2
Yii2 OAuth2 - 例:消費者のFacebook OAuth2
サーチ…
Facebookの開発者にアプリを作成する
[ https://developers.facebook.com/](https://developers.facebook.com/)に移動してアプリを作成します。
[ Add product
をAdd product
クリックし、 Facebook Login
を選択します
yii2-authclientをインストールする
この拡張機能をインストールする前に、yii2-appをインストールする必要があります。この例では、yii2-basicテンプレートを使用します。 ここにインストールするためのガイド。
走る
composer require --prefer-dist yiisoft/yii2-authclient
または追加する
"yiisoft/yii2-authclient": "~2.1.0"
あなたのcomposer.json
require
セクションにcomposer.json
。
config authClientCollection
を設定components
追加します。
return [
'components' => [
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'clientId' => 'facebook_client_id',
'clientSecret' => 'facebook_client_secret',
],
],
]
],
// ...
];
facebook_client_id
はアプリケーションIDで、 facebook_client_secret
はアプリの秘密です。
認証アクションを追加してコールバックを設定する
- 追加ボタン
Login as facebook account
ビューにLogin as facebook account
ログイン:
ビューフォルダのsite/login.php
を編集し、ページの内容にこれらの行を追加しますlogin:
<?= yii\authclient\widgets\AuthChoice::widget([ 'baseAuthUrl' => ['site/auth'], 'popupMode' => false, ]) ?>
上記では、 SiteController
auth
アクションがOAuth2フローを処理するように設定しています。
今度はそれを作成します。
class SiteController extends Controller
{
public function actions()
{
return [
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'onAuthSuccess'],
],
];
}
public function onAuthSuccess($client)
{
// do many stuff here, save user info to your app database
}
}
私たちはyii\authclient\AuthAction
を使ってURLを作成し、Facebookのログインページにリダイレクトします。
機能onAuthSuccess
は、ユーザー情報を取得し、アプリにログインするために使用されました。
Facebookのアプリ設定にredirect_urlを追加する
yii2-appでprettyUrlを有効にすると、redirect_uriは次のようになります:
http://<base_url>/web/site/auth
とかなりのURLを無効にする:
http://<base_url>/web/index.php?r=site%2Fauth
例:
onAuthSuccess関数の例
/**
* @param $client ClientInterface
*/
public function onAuthSuccess($client)
{
//Get user info
/** @var array $attributes */
$attributes = $client->getUserAttributes();
$email = ArrayHelper::getValue($attributes, 'email'); //email info
$id = ArrayHelper::getValue($attributes, 'id'); // id facebook user
$name = ArrayHelper::getValue($attributes, 'name'); // name facebook account
//Login user
//For demo, I will login with admin/admin default account
$admin = User::findByUsername('admin');
Yii::$app->user->login($admin);
}
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow