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',
]);

$provider = new OpenIDConnectProvider([
    'clientId'            => 'your-client-id',
    'redirectUri'         => 'https://your-app.example/callback',
    'issuer'              => 'https://your-idp.example',
    'privateKeyPath'      => '/path/to/client-key.pem',
    'dpopPrivateKeyPath'  => '/path/to/dpop-private.pem',
    'dpopPublicKeyPath'   => '/path/to/dpop-public.pem',
]);

// DPoP proofs are automatically 

$claims = $provider->validateIdToken($idTokenJwt, $expectedNonce);

$provider = new OpenIDConnectProvider([
    // ...
    'cacheDir' => '/path/to/cache',          // default: sys_get_temp_dir()/oauth2-oidc/<user-hash>
    'wellKnownCacheTtl' => 86400,            // default: 86400 (24 hours)
    'jwksCacheTtl' => 3600,                  // default: 3600 (1 hour)
]);

$provider = new OpenIDConnectProvider([
    // ...
], [
    'cache' => $yourPsr16Cache, // Must implement Psr\SimpleCache\CacheInterface
]);

$provider = new OpenIDConnectProvider([
    // ...
], [
    'logger' => $yourPsrLogger,
]);

use Hvatum\OpenIDConnect\Client\Provider\OpenIDConnectProvider;

class MyProvider extends OpenIDConnectProvider
{
    public const CLIENT_ASSERTION_TTL = 10; // Override default TTL

    protected function getDefaultScopes(): array
    {
        return ['openid', 'profile', 'my-custom-scope'];
    }

    protected function createResourceOwner(array $response, AccessToken $token)
    {
        return new MyResourceOwner($response);
    }
}

class MyProvider extends OpenIDConnectProvider
{
    protected function getClientAssertionAudience(): string
    {
        return $this->issuerUrl;
    }
}

class MyProvider extends OpenIDConnectProvider
{
    protected function getAuthorizationDetailsForClientAssertion(array $params, ?array $authorizationDetails): ?array
    {
        if (($params['grant_type'] ?? '') !== 'client_credentials') {
            return null;
        }

        return $authorizationDetails;
    }

    protected function shouldSendAuthorizationDetailsInTokenRequestBody(array $params, ?array $authorizationDetails): bool
    {
        return false;
    }
}