본문으로 건너뛰기

시작하기

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+ with openssl and json(어디서나 표준).
  • 선택: curl(없으면 PHP 스트림), 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/의 인터페이스).

비밀을 저장소 밖에: 환경 변수 또는 웹 루트 밖의 config.php.

로그인

PHP
// 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만료·재사용·위조된 콜백, 잘못된 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가 돌아올 때 세션 쿠키가 전송되도록 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 열기