'code', 'client_id' => $googleClientID, 'redirect_uri' => $redirectURL, 'scope' => 'openid email', 'state' => $_SESSION['state'] ); // Redirect the user to Google's authorization page header('Location: ' . $authorizationEndpoint . '?' . http_build_query($params)); die(); } if(isset($_GET['action']) && $_GET['action'] == 'logout') { unset($_SESSION['user_id']); header('Location: '.$redirectURL); die(); } // When Google redirects the user back here, there will be a "code" and "state" // parameter in the query string if(isset($_GET['code'])) { // Verify the state matches our stored state if(!isset($_GET['state']) || $_SESSION['state'] != $_GET['state']) { header('Location: ' . $redirectURL . '?error=invalid_state'); die(); } // Exchange the auth code for a token $ch = curl_init($tokenEndpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'grant_type' => 'authorization_code', 'client_id' => $googleClientID, 'client_secret' => $googleClientSecret, 'redirect_uri' => $redirectURL, 'code' => $_GET['code'] ])); $response = curl_exec($ch); $data = json_decode($response, true); // Note: You'd probably want to use a real JWT library // but this will do in a pinch. This is only safe to do // because the ID token came from the https connection // from Google rather than an untrusted browser redirect // Split the JWT string into three parts $jwt = explode('.', $data['id_token']); // Extract the middle part, base64 decode it, then json_decode it $userinfo = json_decode(base64_decode($jwt[1]), true); $_SESSION['user_id'] = $userinfo['sub']; $_SESSION['email'] = $userinfo['email']; // While we're at it, let's store the access token and id token // so we can use them later $_SESSION['access_token'] = $data['access_token']; $_SESSION['id_token'] = $data['id_token']; $_SESSION['userinfo'] = $userinfo; header('Location: ' . $redirectURL); die(); } // If there is a user ID in the session // the user is already logged in if(!isset($_GET['action'])) { if(!empty($_SESSION['user_id'])) { echo '
User ID: '.$_SESSION['user_id'].'
'; echo 'Email: '.$_SESSION['email'].'
'; echo ''; echo ''; print_r($_SESSION['userinfo']); echo ''; echo '
'; $ch = curl_init('https://www.googleapis.com/oauth2/v3/userinfo'); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer '.$_SESSION['access_token'] ]); curl_exec($ch); echo ''; } else { echo '