To use OAuth2 tokens later, you can choose between two primary storage strategies depending on whether you want to manage the full AccessToken object or just the refresh token string.
Option 1: Store the AccessToken object
By serializing the entire AccessToken object (e.g., into the Symfony session), you can use the $accessToken->hasExpired() method to check if a refresh is necessary before making an API call. This is efficient as it avoids unnecessary network requests.
Option 2: Store the refresh token string
Alternatively, you can store only the refresh token string (e.g., in a database field like user.refresh_token). In this scenario, you must call $client->refreshAccessToken() using the stored string to obtain a new AccessToken object. Note that when you refresh, you should also update your stored refresh token with the new one provided by the new AccessToken object.
Some OAuth2 providers require specific parameters during the initial token acquisition or during the refresh process (for example, to request offline_access scopes). You can pass these as an associative array to the respective methods.
// Option 1: Using the AccessToken object in a session
$accessToken = $client->getAccessToken();
$session->set('access_token', $accessToken);
$accessToken = $session->get('access_token');
if ($accessToken->hasExpired()) {
$accessToken = $client->refreshAccessToken($accessToken->getRefreshToken());
$session->set('access_token', $accessToken);
}
// Option 2: Using the refresh token string in a database
$accessToken = $client->getAccessToken();
$user->setRefreshToken($accessToken->getRefreshToken());
$entityManager->flush();
$accessToken = $client->refreshAccessToken($user->getRefreshToken());
$user->setRefreshToken($accessToken->getRefreshToken());
$entityManager->flush();
// Using extra parameters (e.g., for scopes)
$accessToken = $client->getAccessToken(['scopes' => 'offline_access']);
$accessToken = $client->refreshAccessToken($accessToken->getRefreshToken(), ['scopes' => 'offline_access']);