PHP code example of hvatum / oauth2-openid-connect-client
1. Go to this page and download the library: Download hvatum/oauth2-openid-connect-client library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hvatum / oauth2-openid-connect-client example snippets
use Hvatum\OpenIDConnect\Client\Provider\OpenIDConnectProvider;
$provider = new OpenIDConnectProvider([
'clientId' => 'your-client-id',
'clientSecret' => 'your-client-secret',
'redirectUri' => 'https://your-app.example/callback',
'issuer' => 'https://your-idp.example',
]);
// Step 1: Redirect user to authorization endpoint
if (!isset($_GET['code'])) {
$authUrl = $provider->getAuthorizationUrl([
'scope' => ['openid', 'profile', 'email'],
]);
// Store state and nonce in session for validation
$_SESSION['oauth2_state'] = $provider->getState();
$_SESSION['oauth2_nonce'] = $provider->getNonce();
$_SESSION['oauth2_pkce'] = $provider->getPkceCode();
header('Location: ' . $authUrl);
exit;
}
// Step 2: Handle callback
if ($_GET['state'] !== $_SESSION['oauth2_state']) {
throw new \RuntimeException('Invalid state');
}
// Restore state from session
$provider->setNonce($_SESSION['oauth2_nonce']);
// Exchange code for tokens (iss is used for RFC 9207 mix-up attack protection)
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code'],
'code_verifier' => $_SESSION['oauth2_pkce'],
'iss' => $_GET['iss'] ?? null,
]);
// Get user info (ID token claims merged with userinfo endpoint)
$user = $provider->getResourceOwner($token);
echo $user->getName();
echo $user->getEmail();
$provider = new OpenIDConnectProvider([
'clientId' => 'your-client-id',
'redirectUri' => 'https://your-app.example/callback',
'issuer' => 'https://your-idp.example',
'privateKeyPath' => '/path/to/private-key.pem', // or .jwk
'keyId' => 'your-key-id', // optional if in JWK file
]);
$provider = new OpenIDConnectProvider([
'clientId' => 'your-client-id',
'issuer' => 'https://your-idp.example',
'privateKey' => getenv('OIDC_CLIENT_PRIVATE_KEY'), // raw PEM or JWK JSON
'keyId' => 'your-key-id',
]);