PHP code example of digitalcz / openid-connect

1. Go to this page and download the library: Download digitalcz/openid-connect 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/ */

    

digitalcz / openid-connect example snippets


use DigitalCz\OpenIDConnect\OidcFactory;
use Symfony\Component\HttpClient\HttpClient;

$httpClient = HttpClient::create();

$oidc = OidcFactory::create(
    httpClient: $httpClient,
    issuer: 'https://auth.example.com',
    clientId: 'my-client-id',
    clientSecret: 'my-client-secret',
    redirectUri: 'https://myapp.example.com/callback',
);

use DigitalCz\OpenIDConnect\OidcFactory;
use DigitalCz\OpenIDConnect\Config\IssuerMetadata;
use Symfony\Component\HttpClient\HttpClient;

$httpClient = HttpClient::create();

$issuerMetadata = new IssuerMetadata([
    'authorization_endpoint' => 'https://auth.example.com/authorize',
    'token_endpoint' => 'https://auth.example.com/token',
    'jwks_uri' => 'https://auth.example.com/.well-known/jwks.json',
    'issuer' => 'https://auth.example.com',
]);

$oidc = OidcFactory::create(
    httpClient: $httpClient,
    issuer: $issuerMetadata,
    clientId: 'my-client-id',
    clientSecret: 'my-client-secret',
    redirectUri: 'https://myapp.example.com/callback',
);

$authorizationCode = $oidc->authorizationCode();

// createAuthorizationUrl() auto-generates cryptographically random state, nonce, and PKCE
// code_verifier. Retrieve them from the result and persist in session before redirecting.
$result = $authorizationCode->createAuthorizationUrl();

// IMPORTANT: Store security parameters in session before redirecting.
// - state: must be verified on callback to prevent CSRF attacks
// - nonce: must be passed to fetchTokens() to validate the ID token
// - codeVerifier: must be passed to fetchTokens() when PKCE is enabled (default)
session_start();
$_SESSION['oauth_state'] = $result->state();
$_SESSION['oauth_nonce'] = $result->nonce();
$_SESSION['oauth_code_verifier'] = $result->codeVerifier();

// Redirect user to $result->url()

session_start();

// IMPORTANT: Always validate the state parameter before proceeding.
// A missing or mismatched state indicates a potential CSRF attack.
if (
    empty($_GET['state'])
    || !isset($_SESSION['oauth_state'])
    || !hash_equals($_SESSION['oauth_state'], $_GET['state'])
) {
    throw new RuntimeException('Invalid state parameter - possible CSRF attack.');
}

$code = $_GET['code'];

$tokens = $authorizationCode->fetchTokens(
    code: $code,
    nonce: $_SESSION['oauth_nonce'],
    codeVerifier: $_SESSION['oauth_code_verifier'],
);

// Clear one-time security parameters from session
unset($_SESSION['oauth_state'], $_SESSION['oauth_nonce'], $_SESSION['oauth_code_verifier']);

echo "Access Token: " . $tokens->accessToken() . PHP_EOL;
echo "ID Token: " . $tokens->idToken() . PHP_EOL;
echo "Refresh Token: " . $tokens->refreshToken() . PHP_EOL;

$clientCredentials = $oidc->clientCredentials();
$tokens = $clientCredentials->fetchTokens();

echo "Access Token: " . $tokens->accessToken() . PHP_EOL;

$device = $oidc->deviceAuthorization();

$response = $device->requestDeviceAuthorization();

// Show these to the user, who completes authorization on another device.
echo "Go to: " . $response->verificationUri() . PHP_EOL;
echo "Enter code: " . $response->userCode() . PHP_EOL;

// verificationUriComplete() embeds the code so the user can skip typing it (e.g. as a QR code).
if ($response->verificationUriComplete() !== null) {
    echo "Or open: " . $response->verificationUriComplete() . PHP_EOL;
}

use DigitalCz\OpenIDConnect\Exception\DeviceAuthorizationDeniedException;
use DigitalCz\OpenIDConnect\Exception\DeviceAuthorizationExpiredException;

try {
    $tokens = $device->pollForTokens($response);
    echo "Access Token: " . $tokens->accessToken() . PHP_EOL;
} catch (DeviceAuthorizationDeniedException $e) {
    echo "User denied the request." . PHP_EOL;
} catch (DeviceAuthorizationExpiredException $e) {
    echo "Device code expired - restart the flow." . PHP_EOL;
}

use DigitalCz\OpenIDConnect\ResourceServer\JwtAccessToken;
use DigitalCz\OpenIDConnect\ResourceServer\OpaqueAccessToken;
use DigitalCz\OpenIDConnect\Util\JWT;

$resourceServer = $oidc->resourceServer();

$accessToken = new JwtAccessToken($jwt);
$validatedToken = $resourceServer->introspect($accessToken);

echo "Token is valid for subject: " . $validatedToken->sub() . PHP_EOL;
echo "Token expires at: " . date('Y-m-d H:i:s', $validatedToken->exp()) . PHP_EOL;

$oidc = OidcFactory::create(
    httpClient: $httpClient,
    issuer: 'https://issuer.example.com',
    clientId: 'my-client',
    accessTokenType: 'at+jwt',
);

// Accept a token whose "aud" matches any of the listed audiences.
$oidc = OidcFactory::create(
    httpClient: $httpClient,
    issuer: 'https://issuer.example.com',
    clientId: 'my-client',
    resourceServerAudience: ['service-a', 'service-b'],
);

// Disable the audience check entirely (the "aud" value is no longer verified against anything;
// its presence is still 

use DigitalCz\OpenIDConnect\Exception\InvalidTokenException;

$handler = $oidc->backChannelLogout();

try {
    // $_POST['logout_token'] is the form-encoded parameter sent by the OP
    $logoutToken = $handler->handleLogoutRequest($_POST['logout_token']);
} catch (InvalidTokenException $e) {
    http_response_code(400);
    return;
}

// Terminate the matching session(s). Use sid (this session) and/or sub (all of the user's sessions).
$sid = $logoutToken->sid(); // ?string
$sub = $logoutToken->sub(); // ?string

http_response_code(200);