2016-06-22 13 views
0

私は、CakePHP 3 Web APIとインターフェースするAndroidアプリを構築しています。 RESTful APIはCookieに依存できないため、これを実現するにはJSON Webトークン(JWT)が必要であり、Googleログインを使用する方がはるかに好きです。私は既にGoogleのAPIからトークンを要求するAndroid側を持っていますが、認証用にこのAPIをAPIに組み込む方法がなくなってしまいました。CakePHP REST APIにGoogleログインを統合する方法

このようなチュートリアルは、http://blog.jainsiddharth21.com/2013/04/29/login-with-google-in-cakephp/のように検索しましたが、セッションデータに依存しています。私はCakePHP 3でAPIを構築していますので、ADmad/JwtAuthなどのプラグインのいくつかを見てきましたので、これをGoogle認証を許可するために拡張することもできますが、どうすればよいか分かりません。

+0

このリンクhttps://github.com/hareshpatel1990/cakephp3restapiこれはあなたを助けることを願っています... –

+0

適切でご覧ください残りのAPIはセッションを使用しません。したがって、各リクエストとともに何らかの認証を送信する必要があります.JWTがこれを達成する最善の方法です! – Voycey

+0

@HareshKumarこれは私がリンクした同じチュートリアルのものですが、とにかくそれを正確に追跡してトークンを生成しますが、ここには「Authorization:Bearer my-long-token-here」ヘッダーがあると認証が失敗します。 – tyjkenn

答えて

1

Gmailを使ってログインし、CakePHPの3.xの中で作成したログイン

https://console.developers.google.com/apis/credentials?project=mdpms-187410&organizationId=1095988912954

でGmailを必要

"google/apiclient": "^2.0" 

をインストールする

作曲をログインを許可する特定の電子メールアドレスプロジェクトを作成して秘密鍵とクライアントIDを作成

セット名でのプロジェクトとリダイレクトURL

注: - あなたは、仮想ホストのフォロー・タイプを作成し、ローカルマシンで開発した場合.COMを可能とドメイン を.orgの必要がありますURLをリダイレクト example.comとexample.org

app_globle.php

'Google' => 
[ 
     'googleClientID' => '123456.apps.googleusercontent.com', 
     'googleClientSecret' => 'abcdefghi', 
     'googleRedirectUrl' => 'http://example.com/oauth2callback' 
    ] 

セットの構成ファイル:仮想ホストは、この手順に従ってください その後、作成

/** 
* Gmail login method 
*/ 

    public function googlelogin() 
    { 


$client = new Google_Client(); 
    $client->setClientId(Configure::read('Google.googleClientID')); 
    $client->setClientSecret(Configure::read('Google.googleClientSecret')); 
    $client->setRedirectUri(Configure::read('Google.googleRedirectUrl')); 
    $client->se 

tScopes([ 
      "https://www.googleapis.com/auth/userinfo.profile", 
      'https://www.googleapis.com/auth/userinfo.email' 
     ]); 
     $url = $client->createAuthUrl(); 
     $this->redirect($url); 
    } 

GoogleのリダイレクトURLアクション

/**:

Gmailのログインルート

// Googleのログイン

$routes->connect('/account/google-login', ['controller' => 'Account', 'action' => 'googlelogin'], ['_name' => 'account-google-login']); 


$routes->connect('/oauth2callback', ['controller' => 'Account', 'action' => 'confirmlogin'], ['_name' => 'account-google-redirect-url']); 

Googleのログインアクションコード* Gmailの認証リダイレクトアクション * @returnタイプのGmailの認証データ */

public function confirmlogin() 
    { 
     $client = new Google_Client(); 
     $client->setClientId(Configure::read('Google.googleClientID')); 
     $client->setClientSecret(Configure::read('Google.googleClientSecret')); 
     $client->setRedirectUri(Configure::read('Google.googleRedirectUrl')); 
     $client->setScopes([ 
      "https://www.googleapis.com/auth/userinfo.profile", 
      'https://www.googleapis.com/auth/userinfo.email' 
     ]); 
     $client->setApprovalPrompt('auto'); 
     $usersTable = TableRegistry::get('Users'); 
     if (isset($this->request->query['code'])) { 
      $client->authenticate($this->request->query['code']); 
      $this->request->Session()->write('access_token', $client->getAccessToken()); 
     } 
     if ($this->request->Session()->check('access_token') && ($this->request->Session()->read('access_token'))) { 
      $client->setAccessToken($this->request->Session()->read('access_token')); 
     } 
     if ($client->getAccessToken()) { 
      $this->request->Session()->write('access_token', $client->getAccessToken()); 
      $oauth2 = new Google_Service_Oauth2($client); 
      $user = $oauth2->userinfo->get(); 
      try { 
       if (!empty($user)) { 
        if ((preg_match("/(@example\.com)$/", $user['email'])) || (preg_match("/(@example\.in)$/", $user['email']))) { 
         $result = $usersTable->find('all') 
           ->where(['email' => $user['email']]) 
           ->first(); 
         if (!empty($result)) { 
          $this->AccessControl->setUser($result->toArray(), false); 
          $this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']); 
          $this->redirect(['_name' => 'dashboard']); 
         } else { 
          $data = []; 
          $data['email'] = $user['email']; 
          $data['first_name'] = $user['givenName']; 
          $data['last_name'] = $user['familyName']; 
          $data['socialId'] = $user['id']; 
          $data['role_id'] = Configure::read('Role.loginWithGmailUserRole'); 
          //$data matches my Users table 
          $entity = $usersTable->newEntity($data); 
          if ($usersTable->save($entity)) { 
           $data['id'] = $entity->id; 
           $this->AccessControl->setUser($data, false); 
           $this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']); 
           $this->redirect(['_name' => 'dashboard']); 
          } else { 
           $this->Flash->error(__('Invalid login.')); 
      //redirect to login action 
           $this->redirect(['_name' => 'account-login']); 
          } 
         } 
        } else { 
         $this->Flash->error(__('Your email is invalid for this application.')); 
     //redirect to login action 
         $this->redirect(['_name' => 'account-login']); 
        } 
       } else { 
        $this->Flash->error(__('Gmail infos not found.')); 
     //redirect to login action 
        return $this->redirect(['_name' => 'account-login']); 
       } 
      } catch (\Exception $e) { 
       $this->Flash->error(__('Gmail error.')); 
       return $this->redirect(['_name' => 'account-login']); 
      } 
     } 
    } 
関連する問題