PHP code example of stromcom / auth-client

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

    

stromcom / auth-client example snippets


use Stromcom\AuthClient\Client;
use Stromcom\AuthClient\Configuration;

$auth = new Client(new Configuration(
    clientId:     getenv('AUTH_CLIENT_ID'),
    clientSecret: getenv('AUTH_CLIENT_SECRET'),
    redirectUri:  'https://my-app.stromcom.cz/oauth/callback',
));

// 1. Anywhere a protected page needs auth — start the flow.
session_start();
[$url, $pkce, $state, $nonce] = $auth->beginAuthorization();
$_SESSION['oauth_verifier'] = $pkce->verifier;
$_SESSION['oauth_state']    = $state;
$_SESSION['oauth_nonce']    = $nonce; // null if `openid` is not in scope
header('Location: ' . $url);

// 2. In your /oauth/callback handler — validate state, exchange code.
if (!hash_equals($_SESSION['oauth_state'], $_GET['state'])) {
    exit('CSRF');
}
$tokens = $auth->exchangeCode($_GET['code'], $_SESSION['oauth_verifier']);

// 2b. Verify the OIDC id_token (binds the response to this session via nonce).
$auth->verifyIdToken($tokens->idToken, $_SESSION['oauth_nonce']);
unset($_SESSION['oauth_nonce']);

// 3. Per request — verify the bearer access token (JWKS is cached for 1 h).
$claims = $auth->verify($tokens->accessToken, $auth->configuration->clientId);
if ($claims->hasGroup('translate-editor')) {
    // authorize
}

$auth = new Client(new Configuration(
    clientId:     'svc_ci_xxxxx',
    clientSecret: getenv('AUTH_CLIENT_SECRET'),
));

$tokens = $auth->clientCredentials();

$response = $http->get('https://api.stromcom.cz/v1/things', [
    'headers' => ['Authorization' => $tokens->authorizationHeader()],
]);

$tokens = $auth->refresh($oldRefreshToken);
// The server rotates: the OLD refresh token is invalidated immediately.
// Persist $tokens->refreshToken right away.

header('Location: ' . $auth->logoutUrl('https://my-app.stromcom.cz/'));

$claims = $auth->verify($jwt, $auth->configuration->clientId);

// Identity
$claims->subject;              // sub
$claims->email;                // ?string
$claims->emailVerified;        // ?bool
$claims->name;                 // ?string (display name, scope `profile`)
$claims->givenName;            // ?string (scope `profile`)
$claims->familyName;           // ?string (scope `profile`)
$claims->phoneNumber;          // ?string E.164 (scope `phone`)
$claims->phoneNumberVerified;  // ?bool   (scope `phone`)
$claims->isAdmin;              // bool
$claims->displayName();        // name → email → client_name → sub
$claims->audience();           // first aud
$claims->isExpired();
$claims->secondsUntilExpiration();

// User vs service tokens
$claims->isUser();             // token_use=user
$claims->isService();          // token_use=service
$claims->clientId;             // service token only
$claims->clientName;           // service token only

// Roles (project-scoped: "{prefix}.{role}")
$claims->roles;                                  // list<string>
$claims->hasRole('translator.editor');
$claims->hasAnyRole('translator.editor', 'translator.admin');
$claims->hasAllRoles('deploy.admin', 'deploy.viewer');
$claims->hasProjectRole('translator', 'editor'); // == hasRole('translator.editor')
$claims->rolesForProject('translator');          // ['editor', 'admin']  (prefix stripped)

// Groups (free-form labels)
$claims->groups;
$claims->hasGroup('vip-users');
$claims->hasAnyGroup('beta', 'early-access');
$claims->hasAllGroups('beta', 'vip-users');

// Scopes
$claims->scopes;
$claims->hasScope('email');

// Guard helpers — throw AuthorizationException if missing
$claims->

use Stromcom\AuthClient\Jwks\ApcuJwksCache;     // Lambda / FPM
use Stromcom\AuthClient\Jwks\InMemoryJwksCache; // CLI / workers
use Stromcom\AuthClient\Jwks\FileJwksCache;     // fallback

$auth = new Client($configuration, jwksCache: new ApcuJwksCache());