С чего начать
PHP SDK
identvia/identvia-php 1.1.1 входит пользователей через OpenID Connect. Чистый PHP 8.1+, без фреймворка, на shared hosting.
Скопируйте промпт для своего ИИ-агента
Пользуетесь агентом для написания кода? Этот промпт направит его к этой документации и перечислит правила, которым он обязан следовать. Проверяйте написанный им код, как любой другой.
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.
You are helping me add "Sign in with Identvia" to my app (Laravel). 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: Laravel. Use the official SDK identvia/identvia-php (framework-agnostic) from a small service class bound in a service provider, not a hand-written OAuth client. Add GET /auth/identvia/redirect and GET /auth/identvia/callback routes in the web middleware group. After the callback, find-or-create the user by the Identvia sub (not by email), call Auth::login() and $request->session()->regenerate(). Put the client secret in .env and config/services.php.
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.
You are helping me add "Sign in with Identvia" to my app (Symfony). 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: Symfony. Use the official SDK identvia/identvia-php wrapped in a service, plus a custom authenticator (AbstractAuthenticator) on the callback route. Map users by the Identvia sub, not email. Keep the client secret in Symfony secrets or env vars, never in committed config.
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.
You are helping me add "Sign in with Identvia" to my app (Node.js). 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: Node.js. There is no Identvia JavaScript SDK; use a certified OpenID Connect relying-party library (for example openid-client) with discovery from the issuer. Use the authorization code flow with PKCE (S256), state and nonce, keep tokens server-side in the session store, and regenerate the session id after sign-in.
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.
You are helping me add "Sign in with Identvia" to my app (Python). 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: Python. There is no Identvia Python SDK; use a maintained OpenID Connect client library (for example Authlib) with discovery from the issuer. Use the authorization code flow with PKCE (S256), state and nonce, and keep tokens server-side.
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 streams) и apcu (иначе кэш ключей в файлах).
- Одна зависимость: firebase/php-jwt для проверки подписей. SDK сам криптографию не реализует.
Установка
composer require identvia/identvia-phpИли загрузите zip через File Manager cPanel и подключите vendor/autoload.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', // необязательно; по умолчанию: системный temp
'leeway' => 60, // допустимый сдвиг часов, секунды
'timeout' => 10, // Таймаут HTTP, секунды
]);| Параметр | Примечания |
|---|---|
| token_auth | client_secret_basic (по умолчанию) или client_secret_post |
| ca_bundle | Путь к CA-файлу, если хранилище сертификатов хоста устарело. Проверку TLS нельзя отключить. |
| cache, http, state_store | Свой кэш, HTTP-клиент или хранилище state (интерфейсы в src/). |
Держите секрет вне репозитория: переменные окружения или config.php вне web root.
Войти
// login.php: отправляет пользователя в Identvia (state, nonce и PKCE обрабатываются за вас)
$identvia->redirectToSignIn([
'return_to' => '/account', // необязательно; принимаются только same-site пути
// '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 | Истёкший, повторно использованный или поддельный callback; неверный issuer | Начать вход снова |
| TokenException | Обмен кода не удался (invalid_grant, invalid_client) | Проверьте секрет; начните снова |
| ValidationException | ID token не прошёл проверку | Никогда не входите пользователем; запишите в лог |
| HttpException | Сбой сети или TLS | Повторить позже |
Все расширяют Identvia\Sdk\Exception\IdentviaException.
Userinfo, refresh, revoke, logout
$claims = $identvia->userinfo($tokens->accessToken, $signIn->sub());
// Нужен scope offline_access. Identvia ротирует refresh tokens: всегда сохраняйте новый.
$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 в callback (RFC 9207) — защита от смешения провайдеров идентичности.
- Подпись ID token ключами Identvia (только RS256/ES256, никогда none или HMAC); ключи кэшируются час и перезапрашиваются один раз при ротации.
- iss, aud, azp, exp, iat, nonce, auth_time против max_age и at_hash.
- HTTPS с проверкой сертификата при каждом вызове; http:// только для localhost.
Сессии
SDK хранит незавершённые входы в PHP-сессии и запускает при необходимости. Cookie сессии должна уходить при возврате от Identvia — используйте SameSite=Lax (не Strict). После успешного входа вызовите session_regenerate_id(true).
Пример: Identvia Notes
Полное приложение со строгим CSP, кнопкой, входом/выходом и заметками на пользователя. В zip: examples/notes-app.
cd identvia-php/examples/notes-app
cp config.example.php config.php # вставьте client ID и секрет
php -S localhost:9999 -t public # затем откройте http://localhost:9999