PHP code example of studio-design / auth-sdk-php

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

    

studio-design / auth-sdk-php example snippets


$config = Studio\Auth\Configuration::getDefaultConfiguration()
    ->setHost('https://your-auth-server.example.com');


fig = Studio\Auth\Configuration::getDefaultConfiguration()
    ->setHost('https://your-auth-server.example.com')
    ->setAccessToken('YOUR_ACCESS_TOKEN');

$adminApi = new Studio\Auth\Api\AdminApi(
    new GuzzleHttp\Client(),
    $config,
);

try {
    $result = $adminApi->listOrganizations();
    print_r($result);
} catch (Studio\Auth\ApiException $e) {
    echo 'Exception: ', $e->getMessage(), PHP_EOL;
}


fig = Studio\Auth\Configuration::getDefaultConfiguration()
    ->setHost('https://your-auth-server.example.com')
    ->setUsername('YOUR_CLIENT_ID')
    ->setPassword('YOUR_CLIENT_SECRET');

$authApi = new Studio\Auth\Api\AuthApi(
    new GuzzleHttp\Client(),
    $config,
);

try {
    $result = $authApi->introspectToken('YOUR_TOKEN');
    print_r($result);
} catch (Studio\Auth\ApiException $e) {
    echo 'Exception: ', $e->getMessage(), PHP_EOL;
}


Google\Auth\Credentials\GCECredentials;
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Studio\Auth\ClientAssertion\ClientAssertionBuilder;
use Studio\Auth\ClientAssertion\Kms\KmsClientAdapter;
use Studio\Auth\ClientAssertion\Kms\KmsClientAssertionSigner;
use Studio\Auth\ClientAssertion\Kms\KmsKeyVersionInventory;

// 実行 SA(metadata server)の資格情報を明示する。ADC が鍵ファイルに解決される環境で、
// 鍵ファイルの SA に署名権限を付けないため。
$kms = new KmsClientAdapter(new KeyManagementServiceClient(['credentials' => new GCECredentials()]));

// $cache は PSR-16 CacheInterface(Laravel なら Cache::store())。鍵バージョン一覧を 5 分キャッシュし、
// KMS 障害時は最後に取れた値を使い続ける。TTL を付けずに保存した項目を消さないストアを渡すこと(下記)。
$inventory = new KmsKeyVersionInventory($kms, 'projects/PROJECT/locations/asia-northeast1/keyRings/RING/cryptoKeys/KEY', $cache);

$builder = new ClientAssertionBuilder(
    clientId: 'YOUR_CLIENT_ID',
    issuer: 'https://auth.studio.design',   // discovery の issuer。aud に入る
    signer: new KmsClientAssertionSigner($kms, $inventory),
);

$config  = Studio\Auth\Configuration::getDefaultConfiguration()->setHost('https://auth.studio.design');
$authApi = new Studio\Auth\Api\AuthApi(new GuzzleHttp\Client(), $config);

$result = $authApi->introspectToken(
    'YOUR_TOKEN',
    null,
    'YOUR_CLIENT_ID',
    ClientAssertionBuilder::ASSERTION_TYPE,
    $builder->build(),   // 呼び出しごとに組み立てる(jti は使い捨て、有効期間 70 秒)
);


Google\ApiCore\ApiException;
use Google\Auth\Credentials\GCECredentials;
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Rpc\Code;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\Promise\Create;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Studio\Auth\ClientAssertion\ClientAssertionBuilder;
use Studio\Auth\ClientAssertion\Kms\KmsCallBudget;
use Studio\Auth\ClientAssertion\Kms\KmsClientAdapter;
use Studio\Auth\ClientAssertion\Kms\KmsClientAssertionSigner;
use Studio\Auth\ClientAssertion\Kms\KmsKeyVersionInventory;

$budget = new KmsCallBudget(5000);
$http   = new GuzzleHttp\Client(['http_errors' => false]);

// metadata server(トークン取得)と KMS の REST が共有する送信処理。送信の直前に残り時間を timeout にし、
// 通信の失敗と 2xx 以外(3xx を含む)は、本文・headers・previous を持たない固定の ApiException にする。
$send = static function (RequestInterface $request, array $options = []) use ($http, $budget): ResponseInterface {
    try {
        $response = $http->send($request, $budget->httpOptions($options));
    } catch (TransferException) {
        throw new ApiException('KMS transport unavailable', Code::UNAVAILABLE, 'UNAVAILABLE');
    }

    $budget->remainingMillis();   // 期限を過ぎて届いた応答は使わない(DEADLINE_EXCEEDED)

    if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {
        throw new ApiException('KMS transport unavailable', Code::UNAVAILABLE, 'UNAVAILABLE');
    }

    return $response;
};

// 一覧の各ページ・各公開鍵・署名の RPC の直前に、残り時間を timeout にしてリトライを無効にした call options を作る。
$kms = new KmsClientAdapter(new KeyManagementServiceClient([
    'credentials'       => new GCECredentials(),
    'credentialsConfig' => ['authHttpHandler' => $send],
    'transport'         => 'rest',
    'transportConfig'   => ['rest' => [
        'httpHandler' => static fn (RequestInterface $request, array $options = []) => Create::promiseFor($send($request, $options)),
    ]],
]), $budget->callOptions(...));

// inventory・signer・builder はこの $kms から作る(期限の無い adapter を持ったものを使い回さない)。
// $cache は前節と同じ、TTL 省略時に無期限で保存する PSR-16 ストア。
$inventory = new KmsKeyVersionInventory($kms, 'projects/PROJECT/locations/asia-northeast1/keyRings/RING/cryptoKeys/KEY', $cache);
$builder   = new ClientAssertionBuilder(
    clientId: 'YOUR_CLIENT_ID',
    issuer: 'https://auth.studio.design',
    signer: new KmsClientAssertionSigner($kms, $inventory),
);

$assertion = $budget->run(fn () => $builder->build());
$jwks      = $budget->run(fn () => $inventory->jwks());

$url = Studio\Auth\SecuritySettings::url('https://auth.studio.design');
// https://auth.studio.design/account/security

use Studio\Auth\ApiException;
use Studio\Auth\Exception\NotFoundException;

try {
    $organization = $adminApi->getOrganization('org_xxxxx');
} catch (NotFoundException $e) {
    // 404: 指定した組織が存在しない
    echo $e->getProblem()?->getTitle(), PHP_EOL;
} catch (ApiException $e) {
    // その他の API エラー(未マップのステータス・接続エラー含む)
    echo $e->getCode(), ': ', $e->getMessage(), PHP_EOL;
}
bash
composer