gpt4 book ai didi

cakephp - 在 CakePHP 2.3 中使用 OAuth 进行身份验证

转载 作者:行者123 更新时间:2023-12-04 21:45:34 26 4
gpt4 key购买 nike

我有一个 CakePHP 应用程序,我希望我的用户能够使用 OAuth 登录。

我似乎让 OAuth 对话正常工作,因为我正在从它的末尾获取用户信息,并且可以将 token 保存到我的 users表不错。

我的问题可能很愚蠢,但我正在努力解决何时需要使用我获得的 token 。我是否应该将用户的 ID 存储在 cookie 中,并且每当他们“回到”我的网站时,从数据库中获取他们的 token 并让我们重新检查他们的详细信息?

我没有为使用 OAuth 的用户获得任何类型的密码,所以我应该为这些人绕过 Auth,还是使用其中一个 token 作为 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)。

关于cakephp - 在 CakePHP 2.3 中使用 OAuth 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15090917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com