"authorization_code", "code" => $code, "redirect_uri" => self::getRedirectUri(), "client_id" => self::$client_id, "client_secret" => self::$client_secret, ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $token_endpoint); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/x-www-form-urlencoded", ]); $response = curl_exec($ch); curl_close($ch); $token_data = json_decode($response, true); if (isset($token_data["access_token"])) { $_SESSION["access_token"] = $token_data["access_token"]; $_SESSION["id_token"] = $token_data["id_token"] ?? null; $_SESSION["refresh_token"] = $token_data["refresh_token"] ?? null; Flight::redirect($redirect_url); } else { Flight::halt(500, "Failed to obtain access token"); } } else { // Show login page $auth_endpoint = self::getDiscoveryEndpoint( "authorization_endpoint", ); $state = bin2hex(random_bytes(16)); $_SESSION["oauth_state"] = $state; $params = [ "response_type" => "code", "client_id" => self::$client_id, "redirect_uri" => self::getRedirectUri(), "scope" => "openid profile email", "state" => $state, ]; $login_url = $auth_endpoint . "?" . http_build_query($params); echo '
Please click the button below to authenticate
Login with OIDC '; } } public static function user() { self::init(); if (!isset($_SESSION["access_token"])) { return null; } $userinfo_endpoint = self::getDiscoveryEndpoint("userinfo_endpoint"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $userinfo_endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Authorization: Bearer " . $_SESSION["access_token"], ]); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($http_code === 200) { return json_decode($response, true); } return null; } public static function logout() { self::init(); // Clear session if (isset($_SESSION["access_token"])) { unset($_SESSION["access_token"]); } if (isset($_SESSION["id_token"])) { unset($_SESSION["id_token"]); } if (isset($_SESSION["refresh_token"])) { unset($_SESSION["refresh_token"]); } Flight::redirect("/"); } private static function getDiscoveryEndpoint($endpoint) { $discovery_url = rtrim(self::$oidc_issuer, "/") . "/.well-known/openid-configuration"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $discovery_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $response = curl_exec($ch); curl_close($ch); $discovery = json_decode($response, true); if (!isset($discovery[$endpoint])) { throw new Exception( "Endpoint {$endpoint} not found in OIDC discovery: " . $discovery_url, ); } return $discovery[$endpoint]; } }