LoginSignup
11
10

More than 5 years have passed since last update.

Yii2でちょろいOAuthログイン

Last updated at Posted at 2014-12-12

yiisoft/yii2-authclientという公式のエクステンションでOAuthログインの実装がちょろいという話

twitterやfbでのログインを実装しようとするとどのAuthクライアント使うかとか、それぞれ別のエクステンション用意したりして面倒臭かったりするのですが、公式のOAuthエクステンションがすごい

まず標準のクライアントが多い

  • Facebook
  • GitHub
  • GoogleOAuth
  • GoogleOpenId
  • LinkedIn
  • Live
  • Twitter
  • VKontakte
  • YandexOAuth
  • YandexOpenId

Yandexとか日本に馴染みのない名前ですが、何かというとロシアの最大手検索サービスだそうです。Yiiが旧共産圏で人気なので需要あるんでしょうねきっと。

fbとtwitterとgithubとgoogleあればもう困らないかなという気もしますが、コレ以外のサイトを利用する場合も独自にクライアントを書けば対応できます。
クライアントの設定もかなりシンプルなので簡単に対応出来そうです。(これはまた別の記事で)

組み込みも簡単。
composerでauthclientを追加して

composer.json
         "php": ">=5.4.0",
         "yiisoft/yii2": "*",
         "yiisoft/yii2-bootstrap": "*",
-        "yiisoft/yii2-swiftmailer": "*"
+        "yiisoft/yii2-swiftmailer": "*",
+        "yiisoft/yii2-authclient": "*"
     },

設定に利用するOAuthクライアント追加して

config/web.php
     'basePath' => dirname(__DIR__),
     'bootstrap' => ['log'],
     'components' => [
+        'authClientCollection' => [
+            'class' => 'yii\authclient\Collection',
+            'clients' => [
+                'google' => [
+                    'class' => 'yii\authclient\clients\GoogleOpenId'
+                ],
+                'facebook' => [
+                    'class' => 'yii\authclient\clients\Facebook',
+                    'clientId' => '<<FaceBookAppClientId>>', // Facebookで作成したアプリのキー情報
+                    'clientSecret' => '<<FaceBookAppClientSecret>>',
+                ],
+            ],
+        ],

ルートに当たるコントローラにコールバックを追加

controllers/SiteController.php
                 'class' => 'yii\captcha\CaptchaAction',
                 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
             ],
+            'auth' => [
+                'class' => 'yii\authclient\AuthAction',
+                'successCallback' => [$this, 'successCallback'],
+            ],
         ];
     }

+    public function successCallback($client)
+    {
+        $attributes = $client->getUserAttributes();
+        // ここでログイン処理。終わると勝手にリダイレクトする
+    }
+

viewにログインボタン追加

views/site/login.php
 <div class="site-login">
     <h1><?= Html::encode($this->title) ?></h1>

+    <?= yii\authclient\widgets\AuthChoice::widget([
+            'baseAuthUrl' => ['site/auth']
+        ]) ?>
+
     <p>Please fill out the following fields to login:</p>

これだけで標準クライアントならボタンまで勝手に出してくれる

スクリーンショット 2014-12-12 23.08.31.png

すごい!革命的なちょろさだ!

ただし簡単なのはここまで。複数手段でログインさせようとしてユーザを結びつけたりするとなるといろいろ気をつかう点もでてくるので各々がんばってください!

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10