跳到正文

快速开始

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 streams)和 apcu(否则密钥缓存在文件)。
  • 唯一依赖: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/)。

密钥勿进代码仓库:用环境变量,或 web 根外的 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 token 未通过检查切勿让用户登录;记录日志
HttpException网络或 TLS 失败稍后重试

均扩展 Identvia\Sdk\Exception\IdentviaException。

Userinfo、refresh、revoke、logout

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

// 需要 offline_access 范围。Identvia 轮换 refresh token:始终保存新的。
$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),防御身份提供方混淆。
  • 用 Identvia 公布的密钥验证 ID token 签名(仅 RS256/ES256,绝不用 none 或 HMAC);密钥缓存一小时,轮换时再取一次。
  • iss、aud、azp、exp、iat、nonce、auth_time 对照 max_age,以及 at_hash。
  • 每次调用均 HTTPS 并验证证书;仅对 localhost 接受 http://。

会话

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