使用OAuth进行CakePHP 2.3身份验证
发布时间:2020-12-13 22:47:42 所属栏目:PHP教程 来源:网络整理
导读:我有一个Cake PHP应用程序,我希望我的用户能够使用OAuth登录. 我似乎让OAuth会话正常工作,因为我收到了用户信息,并且可以将令牌保存到我的用户表中. 我的问题可能是一个愚蠢的问题,但是当我需要使用我给出的令牌时,我正在尝试解决问题.我是否应该将用户的ID
我有一个Cake
PHP应用程序,我希望我的用户能够使用OAuth登录.
我似乎让OAuth会话正常工作,因为我收到了用户信息,并且可以将令牌保存到我的用户表中. 我的问题可能是一个愚蠢的问题,但是当我需要使用我给出的令牌时,我正在尝试解决问题.我是否应该将用户的ID存储在cookie中,每当他们“返回”我的网站时,从数据库中获取令牌并让我们重新检查他们的详细信息? 对于使用OAuth的用户,我没有获得任何密码,所以我应该绕过Auth这些人,还是使用其中一个令牌作为CakePHP的密码? 以下是UsersController的login和oauth2callback部分: <?php class UsersController extends AppController { public function login() { if ($this->request->is('post')) { if ($this->Auth->login()) { $this->redirect($this->Auth->redirect()); } else { $this->Session->setFlash(__('Invalid username or password')); } } else { $client = $this->getGoogleClient(); $authUrl = $client->createAuthUrl(); $this->set(array('GoogleAuthUrl' => $authUrl)); } } public function oauth2callback() { $client = $this->getGoogleClient(); if (isset($this->request->query['code'])) { $client->authenticate($this->request->query['code']); $this->Session->write('token',$client->getAccessToken()); $this->redirect('oauth2callback'); return; } if ($this->Session->read('token')) { $client->setAccessToken($this->Session->read('token')); } $accessToken = $client->getAccessToken(); if ($accessToken) { $oauth2 = new Google_Oauth2Service($client); $user = $oauth2->userinfo->get(); $token = json_decode($accessToken); debug($token); debug($user); // We now have a user from Google. Either log them in,or create a new user $id = $this->User->field('id',array('email' => $user['email'],'oauth_id' => $user['id'])); if (empty($id)) { $new_user = $this->User->create(); $new_user['User']['username'] = $user['email']; $new_user['User']['email'] = $user['email']; $new_user['User']['oauth_id'] = $user['id']; $new_user['User']['oauth_token'] = $token->access_token; $new_user['User']['oauth_expires'] = time() + $token->expires_in; $new_user['User']['oauth_id_token'] = $token->id_token; $new_user['User']['oauth_refresh_token'] = $token->refresh_token; $new_user['User']['oauth_created'] = $token->created; if ($this->User->save($new_user)) { $new_user['User']['id'] = $this->User->id; debug($new_user); $this->Session->setFlash(__('Registration complete!')); if ($this->Auth->login($new_user)) { // return $this->redirect($this->Auth->redirectUrl()); } //$this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('There was a problem with your registration. Please,try again.')); } } // The access token may have been updated lazily. $this->Session->write('token',$client->getAccessToken()); } } } 解决方法
向Auth组件添加自定义身份验证的CakePHP方法是创建“自定义身份验证对象”(请参阅??
http://book.cakephp.org).
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |