简体   繁体   English

在会话中保存 OAuth 令牌是否正确?

[英]Is it correct to save OAuth tokens in sessions?

I'm wondering if it's a good idea to save access tokens in session.我想知道将访问令牌保存在 session 中是否是个好主意。

I am developing an application that requires the Google OAuth Access Token (following docs ) to use Calendar.我正在开发一个需要 Google OAuth 访问令牌(以下文档)才能使用日历的应用程序。

$client = new Google_Client();
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->addScope(Google_Service_Calendar::CALENDAR_EVENTS);

$redirect_uri = 'https://...';
$client->setRedirectUri($redirect_uri);
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

$client->setAccessToken($_SESSION['accessToken']);

/* Refresh token when expired */
if ($client->isAccessTokenExpired()) {
    // the new access token comes with a refresh token as well
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
$service = new Google_Service_Calendar($client);
...

Not always the user will be logged into my site, so I have no way to identify the user, so is it a good practice to save the token in the session?并非总是用户会登录到我的站点,因此我无法识别用户,因此将令牌保存在 session 中是否是一个好习惯? When I can identify him, can I save his token to the database, or is it better to follow the pattern and leave everything in session?当我可以识别他时,我可以将他的令牌保存到数据库中,还是按照模式将所有内容留在 session 中更好?

User sessions can be structured in any way you'd like.用户会话可以按照您喜欢的任何方式构建。

Your objective is to use the right OAuth Token for the right user.您的目标是为正确的用户使用正确的 OAuth 令牌。

You could do this by creating a Session for the user and storing the token there, however, those sessions might expire earlier than the tokens you are storing in them.您可以通过为用户创建 Session 并将令牌存储在那里来做到这一点,但是,这些会话可能比您存储在其中的令牌更早到期。

You could also store your refresh tokens in your database and just store a reference number (a custom ID) that helps you tie that session with the user you are serving.您还可以将刷新令牌存储在数据库中,并仅存储一个参考号(自定义 ID),以帮助您将 session 与您所服务的用户联系起来。 This can be useful if you already have a user-account structure in place.如果您已经有一个用户帐户结构,这将很有用。

This official documentation is an interesting read if you want to understand more about your situation.如果您想更多地了解您的情况,这份官方文档是一本有趣的书。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM