2016-06-22 31 views
0

我正在構建與CakePHP 3 Web API接口的Android應用程序。由於RESTful API不能依賴於Cookie,因此我知道我需要JSON Web令牌(JWT)來實現此目的,並且更願意使用Google登錄。我已經得到Android方面的要求,從谷歌的API的令牌,但現在我迷失在如何將其納入我的API認證。如何在CakePHP REST API上集成Google登錄

我搜索了一些教程,比如這個:http://blog.jainsiddharth21.com/2013/04/29/login-with-google-in-cakephp/,但它依賴於會話數據。我在CakePHP 3中構建了API,因此我查看了一些插件,例如ADmad/JwtAuth,所以也許我可以在此上擴展以允許谷歌身份驗證,但我不知道如何。

+0

請看看這個鏈接https://github.com/hareshpatel1990/cakephp3restapi希望這將幫助你... –

+0

一個適當的rest API不會使用會話,因此您需要發送某種身份驗證以及每個請求,JWT是完成此操作的最佳方式! – Voycey

+0

@HareshKumar這是來自我鏈接到的相同的教程,並且無論如何,我完全按照它來生成令牌,但是當我擁有標頭'Authorization:Bearer my-long-token-here'時,認證仍然失敗。 – tyjkenn

回答

1

登錄Gmail和特定的電子郵件地址,以允許在CakePHP中3.X登錄

作曲家安裝

"google/apiclient": "^2.0" 

需要與登錄的Gmail

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

創建項目並創建密鑰和客戶端ID

項目集名稱和URL重定向

注: - 重定向URL必須是.com和.org等域名 如果您在本機開發再創建虛擬主機的後續型 example.com和example.org

虛擬主機再創建 按照此步驟:

設置配置文件中app_globle.php

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

的Gmail登錄路由

//谷歌登錄

$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']); 

谷歌登錄動作代碼:

/** 
* 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); 
    } 

谷歌重定向URL操作

/** * Gmail的權威性重定向動作 * @返回類型的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']); 
      } 
     } 
    }