本文へスキップ

はじめに

PHP SDK

identvia/identvia-php 1.1.1 は OpenID Connect でサインインします。素の PHP 8.1+、フレームワーク不要、共有ホスティング可。

AI エージェント用のプロンプトをコピー

コーディングエージェントを使っていますか?このプロンプトはエージェントをこのドキュメントに案内し、守るべきルールを示します。エージェントが書いたコードも、ほかのコードと同じようにレビューしてください。

You are helping me add "Sign in with Identvia" to my app (PHP). Identvia is an OpenID Connect provider.

Read these first (they are plain Markdown and are the source of truth; prefer them over anything you remember):
- https://id.identvia.com/developers/docs/quickstart.md
- https://id.identvia.com/developers/docs/oidc.md
- https://id.identvia.com/developers/docs/security.md
- Discovery: https://id.identvia.com/.well-known/openid-configuration

Stack: plain PHP 8.1+ (no framework). Use the official SDK identvia/identvia-php (composer require identvia/identvia-php, or the zip with vendor/ from https://id.identvia.com/developers/docs/php for hosts without Composer). Create identvia.php (config), login.php (redirectToSignIn), callback.php (handleCallback, then session_regenerate_id(true) and store sub) and logout.php. Read secrets from environment variables or a config file outside the web root.

Requirements:
1. Authorization code flow with PKCE (S256 only), a random state and a nonce per sign-in. No implicit flow.
2. Validate the ID token: RS256 signature from the JWKS, iss = https://id.identvia.com, aud contains my client_id, exp/iat, and the nonce.
3. Identify users by sub (it is pairwise: different for every app). Treat email as optional, because the person may choose not to share it.
4. Redirect URIs must match exactly. Keep the client secret and refresh tokens server-side; never log tokens.
5. Ask only for the scopes I need (openid, plus email/profile if used). Handle the user canceling (error=access_denied) gracefully.

Optional, only if I ask for AI-agent access later:
- AgentPass (agents acting for a user with single-use, holder-bound passes): https://id.identvia.com/developers/docs/agentpass.md
- MCP server for agent clients: https://id.identvia.com/developers/docs/mcp.md
- Token exchange, rich authorization requests and CIBA: https://id.identvia.com/developers/docs/delegation.md

Before writing code, tell me which files you will add or change. Don't invent endpoints or options that aren't in the docs; if something is unclear, ask me.

要件

  • PHP 8.1+ と openssl・json(どこでも標準)。
  • 任意: curl(なければ PHP ストリーム)と apcu(なければ鍵キャッシュはファイル)。
  • 依存は 1 つ: 署名検証用 firebase/php-jwt。SDK 自身は暗号を実装しません。

インストール

Terminal
composer require identvia/identvia-php

または cPanel のファイルマネージャで zip を上げ vendor/autoload.php を読み込む。

構成

PHP
$identvia = new Identvia\Sdk\Identvia([
    'issuer'        => 'https://id.identvia.com',          // 必須
    'client_id'     => 'oid_…',             // 必須
    'client_secret' => 'ivs_…',             // 機密アプリのみ
    'redirect_uri'  => 'https://example.com/callback.php', // 完全一致必須
    'scopes'        => ['email', 'profile'], // openid は常に追加
    'cache_dir'     => __DIR__ . '/../storage/identvia', // 任意。既定: システムの一時ディレクトリ
    'leeway'        => 60,                  // 許容する時刻ずれ(秒)
    'timeout'       => 10,                  // HTTP タイムアウト(秒)
]);
オプション注意
token_authclient_secret_basic(既定)または client_secret_post
ca_bundleホストの証明書ストアが古い場合の CA ファイルパス。TLS 検証はオフにできません。
cache、http、state_store独自のキャッシュ、HTTP クライアント、状態ストアを持ち込可能(インターフェースは src/)。

シークレットをリポジトリ外に: 環境変数、またはウェブルート外の config.php。

サインイン

PHP
// login.php: ユーザーを Identvia へ(state・nonce・PKCE は代行)
$identvia->redirectToSignIn([
    'return_to' => '/account',   // 任意。同一サイトのパスのみ受理
    // 'prompt'  => 'login',      // 新しいサインインを強制
    // 'max_age' => 300,          // 直近 5 分以内のサインインを要求
]);

// callback.php: 完了処理
$signIn = $identvia->handleCallback($_GET);
$signIn->sub();           // the user's ID for your app
$signIn->email();         // 共有されなければ null
$signIn->emailVerified();
$signIn->name();
$signIn->amr();           // e.g. ['hwk', 'user'] for a passkey
$signIn->tokens;          // TokenSet: accessToken, refreshToken, idToken, expiresAt
$signIn->returnTo;

エラー

例外日時どうするか
AuthorizationExceptionユーザーがキャンセル(userCancelled())または Identvia がエラーわかりやすいメッセージを表示
InvalidStateException期限切れ・再利用・偽造コールバック、誤った issuerサインインをやり直す
TokenExceptionコード交換失敗(invalid_grant、invalid_client)シークレットを確認してやり直す
ValidationExceptionID トークンの検査失敗サインインさせずログする
HttpExceptionネットワークまたは TLS 失敗後で再試行

すべて Identvia\Sdk\Exception\IdentviaException を継承。

Userinfo、refresh、revoke、logout

PHP
$claims = $identvia->userinfo($tokens->accessToken, $signIn->sub());

// offline_access スコープが必要。Identvia はリフレッシュをローテーション: 常に新しいものを保存。
$tokens = $identvia->refresh($tokens->refreshToken, $signIn->sub());

$identvia->revoke($tokens->refreshToken);   // サインアウト時

// 任意: Identvia セッションも終了
header('Location: ' . $identvia->logoutUrl($tokens->idToken, 'https://example.com/'));

SDK が検査すること

  • state: 乱数・一回限り・10 分で期限切れ。複数タブで同時サインイン可。
  • PKCE(S256)をすべてのリクエストで使用。機密アプリも含む。
  • コールバックの iss(RFC 9207)。IdP 取り違えを防ぎます。
  • Identvia 公開鍵で ID トークンの 署名(RS256/ES256 のみ。none や HMAC 不可)。鍵は 1 時間キャッシュ、ローテーション時に一度再取得。
  • iss、aud、azp、exp、iat、nonce、auth_time と max_age、at_hash。
  • 毎回 HTTPS と証明書検証。http:// は localhost のみ。

セッション

SDK は保留中のサインインを PHP セッションに保ち、必要なら開始します。Identvia からの戻りでセッション Cookie が送られるよう SameSite=Lax(Strict 不可)。成功後に session_regenerate_id(true)。

サンプル: Identvia Notes

厳格な CSP、ボタン、サインイン/アウト、ユーザーごとのメモを備えた完成アプリ。zip 内 examples/notes-app。

Terminal
cd identvia-php/examples/notes-app
cp config.example.php config.php    # client ID とシークレットを貼り付け
php -S localhost:9999 -t public     # その後 http://localhost:9999 を開く