Cakephp 3.6 oauth 使用 google-plus 重定向问题

Cakephp 3.6 oauth using google-plus redirection problem

美好的一天Mam/Sir

我想知道为什么在 cakephp 中使用 google-plus 登录后我没有重定向到仪表板页面。一切似乎都很好,没有出现错误消息,因此调试代码非常困难。 在我的研究过程中,我发现了这个网站 [http://caketuts.key-conseil.fr/index.php/2015/05/22/integrer-lapi-oauth2-de-google-avec-cakephp-v3/][1]。 我还是 Cakephp 3.6 的新手,这是我第一次在我的项目中实现 oauth google +。

AdminController

    public function googlelogin() {

    $client = new Google_Client();
    $client->setClientId(GOOGLE_OAUTH_CLIENT_ID);
    $client->setClientSecret(GOOGLE_OAUTH_CLIENT_SECRET);
    $client->setRedirectUri(GOOGLE_OAUTH_REDIRECT_URI);

    $client->setScopes(array(
            'https://www.googleapis.com/auth/userinfo.profile',
            'https://www.googleapis.com/auth/userinfo.email'
    ));

    $client->setApprovalPrompt('auto');

    $url = $client->createAuthUrl();
    $this->redirect($url);

}

public function google_login() {

    $client = new Google_Client();
    $client->setClientId(GOOGLE_OAUTH_CLIENT_ID);
    $client->setClientSecret(GOOGLE_OAUTH_CLIENT_SECRET);
    $client->setRedirectUri(GOOGLE_OAUTH_REDIRECT_URI);

    $client->setScopes(array(
            'https://www.googleapis.com/auth/userinfo.profile',
            'https://www.googleapis.com/auth/userinfo.email'
    ));

    $client->setApprovalPrompt('auto');

    if (!empty($this->request->getQuery('code'))) {
        $client->authenticate($this->request->getQuery('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)) {

                $result = $this->Admins->find('all')
                              ->where(['email' => $user['email']])
                              ->first();
                if ($result) {
                    $data = array();
                    $data['email'] = $user['email'];
                    $data['fname'] = $user['givenName'];
                    $data['lname'] = $user['familyName'];
                    $data['social_id'] = $user['id'];
                    $data['avatar'] = $user['picture'];
                    $data['link'] = $user['link'];
                    $data['uuid'] = Text::uuid();
                    $entity = $this->Admins->newEntity($data);

                    if ($this->Admins->save($entity)) {
                        $data['id'] = $entity->id;
                        $this->Auth->setUser($data);
                        $this->redirect($this->Auth->redirectUrl());
                    } else {
                        $this->Flash->error('Unable to connect to google');
                        #return $this->redirect(['action' => 'login']);
                    }
                }

            } else {
                $this->Flash->error('Unable to retrieve google data');
                #return $this->redirect(['action' => 'login']);
            }
        } catch (\Exception $e) {
            $this->Flash->error($e);
            #return $this->redirect(['action' => 'login']);
        }
    }
}

In my view

    <?= $this->Form->create() ?>
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Username" required="" name="username">
        </div>
        <div class="form-group">
            <input type="password" class="form-control" placeholder="Password" required="" name="password">
        </div>
        <button type="submit" class="btn btn-default block full-width m-b">Login</button>

        <!--<a href="#"><small>Forgot password?</small></a>-->
        <a class="btn btn-block google btn-danger" href="<?= $this->Url->build(['action' => 'googlelogin']); ?>"> <i
            class="fa fa-google-plus modal-icons"></i> Login using Google Account </a>

</div>
    <?= $this->Form->end() ?>


  In My AppController


public function initialize()
{
    parent::initialize();
    #$this->loadComponent('Csrf');
    $this->loadComponent('RequestHandler', [
        'enableBeforeRedirect' => false,
    ]);
    $this->loadComponent('Flash');
    $this->viewBuilder()->setLayout('inspinia');
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'username',
                    'password' => 'password'
                ], 
                'userModel' => 'Admins'
            ]
        ],
        #'authError'  => __('Invalid username or password'),
        'loginRedirect' => [
            'controller' => 'Admins',
            'action' => 'dashboard'
        ],
        'logoutRedirect' => [
            'controller' => 'Admins',
            'action' => 'login',
            // 'home'
        ],
        'loginAction' => [
            'controller' => 'Admins',
            'action' => 'login'
        ],
        #'storage' => 'Session',
         //use isAuthorized in Controllers
        'authorize' => ['Controller'],
         // If unauthorized, return them to page they were just on
        'unauthorizedRedirect' => $this->referer()
    ]);

}

public function beforeFilter(Event $event){
    $this->viewBuilder()->setLayout('inspinia');
    $userId = "";
    if($this->Auth->user()){
        $userId = $this->Auth->user('id');
        $username = $this->Auth->user('username');
        $userFname = $this->Auth->user('fname');
        $userLname = $this->Auth->user('lname');
        $userRole = "";
    }

    if($userId) {
        $roles = TableRegistry::get('Roles');
        $userRole = $roles->get($this->Auth->user('role_id'))->name;
    }
    $this->set(compact('userId', 'username', 'userFname', 'userLname', 'userRole'));
}

public function isAuthorized($user)
{

    if (isset($user['role_id']) && $user['role_id'] === 1) {
        return true;
    }

    return false;
}

}

我使用 cakephp/social-auth 解决了这个问题 Here's the link to the plugin