title: Is it correct to save OAuth tokens in sessions?
body: <p>I'm wondering if it's a good idea to save access tokens in session.</p>
  
  <p>I am developing an application that requires the Google OAuth Access Token (following <a href="https://developers.google.com/identity/protocols/OAuth2WebServer#example" rel="nofollow noreferrer">docs</a>) to use Calendar.</p>
  
  <pre class="lang-php prettyprint-override"><code>$client = new Google_Client();
  $client-&gt;setAuthConfig('credentials.json');
  $client-&gt;setAccessType('offline');
  $client-&gt;addScope(Google_Service_Calendar::CALENDAR_EVENTS);
  
  $redirect_uri = 'https://...';
  $client-&gt;setRedirectUri($redirect_uri);
  if (! isset($_GET['code'])) {
    $auth_url = $client-&gt;createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
  } else {
    $client-&gt;authenticate($_GET['code']);
    $_SESSION['access_token'] = $client-&gt;getAccessToken();
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
  }
  
  $client-&gt;setAccessToken($_SESSION['accessToken']);
  
  /* Refresh token when expired */
  if ($client-&gt;isAccessTokenExpired()) {
      // the new access token comes with a refresh token as well
      $client-&gt;fetchAccessTokenWithRefreshToken($client-&gt;getRefreshToken());
  }
  $service = new Google_Service_Calendar($client);
  ...
  </code></pre>
  
  <p>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?</p>