我有一个 CakePHP 应用程序,我希望我的用户能够使用 OAuth 登录。
我似乎 OAuth 对话工作正常,因为我正在从其末尾获取用户信息,并且可以将令牌保存到我的users
表罚款。
我的问题可能是一个愚蠢的问题,但我正在尝试弄清楚何时需要使用给我的令牌。我是否应该将用户的 ID 存储在 cookie 中,并且每当他们“返回”我的网站时,从数据库中获取他们的令牌并使用它来重新检查他们的详细信息?
我没有通过 OAuth 获得用户的任何密码,所以我应该绕过这些人的 Auth,还是使用其中一个令牌作为 CakePHP 的密码?
以下是我的 UsersController 的登录和 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());
}
}
}
CakePHP 将自定义身份验证添加到 Auth 组件的方法是创建一个“自定义身份验证对象”(请参阅http://book.cakephp.org http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#creating-custom-authentication-objects).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)