简体   繁体   中英

Is it correct to save OAuth tokens in sessions?

I'm wondering if it's a good idea to save access tokens in session.

I am developing an application that requires the Google OAuth Access Token (following docs ) to use Calendar.

$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? 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?

User sessions can be structured in any way you'd like.

Your objective is to use the right OAuth Token for the right user.

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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