設定 & 応用
createAuthrim 設定
Section titled “createAuthrim 設定”import { createAuthrim } from '@authrim/sveltekit';
const auth = await createAuthrim({ issuer: 'https://auth.example.com', clientId: 'my-app', authMode: 'server', storage: { prefix: 'authrim', storage: 'memory', },});AuthrimConfig
Section titled “AuthrimConfig”| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
issuer | string | 必須 | AuthrimサーバーURL |
clientId | string | 必須 | OAuthクライアントID |
tenantId | string | — | ブラウザDPoP鍵素材のスコープに使うテナントID |
authMode | 'server' | 'browser' | 'server' | トークン処理モード |
profile | 'auto' | 'token' | 'cookie' | 'auto' | フレームワークレベルのセッションプロファイル |
serverSession | ServerMediatedSessionOptions | 下記参照 | 同一オリジンCookieセッションエンドポイント |
csrf | { cookieName?: string; headerName?: string } | 下記参照 | Cookieリクエスト向けdouble-submit CSRF設定 |
storage | StorageOptions | {} | クライアントサイドストレージ設定 |
browserPublicClientMode | 'strict' | 'cookie_fallback' | 'legacy' | モード依存 | ブラウザ公開クライアントのセキュリティモード |
browserRefreshTokenPolicy | 'disabled' | 'dpop_bound' | 'disabled' | ブラウザリフレッシュトークンポリシー |
enableOAuth | boolean | false | OAuth/OIDC名前空間を有効化 |
silentLoginRedirectUri | string | {origin}/callback.html | OAuthサイレントログインのコールバックURI |
Auth Mode
Section titled “Auth Mode”| モード | 動作 | 用途 |
|---|---|---|
'server' | Direct Auth artifactを同一オリジンのSvelteKitエンドポイントでredeemします。OAuth/OIDCトークンはブラウザJSに出さず、アプリはHttpOnly Cookieセッションを使います。 | SvelteKitアプリのデフォルト |
'browser' | ブラウザSDKがOAuth/OIDCトークン素材を直接保持します。 | 明示的なブラウザトークン連携 |
serverモードでは profile: 'auto' がCookieプロファイルに解決されます。browserモードでブラウザ保持トークンフローが必要な場合は profile: 'token' を明示してください。
ServerMediatedSessionOptions
Section titled “ServerMediatedSessionOptions”| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
exchangeEndpoint | string | '/authrim/session/exchange' | Direct Auth artifactをredeemし、HttpOnlyセッションCookieを設定 |
sessionEndpoint | string | '/authrim/session' | 現在のCookie-backed sessionを返す |
logoutEndpoint | string | '/authrim/session/logout' | Cookie-backed sessionをクリア |
checkOnMount | boolean | false | SSRセッションがない場合に AuthProvider がmount時にCookieセッションを取得できるようにする |
credentials | RequestCredentials | 'same-origin' | 同一オリジンセッションリクエストのcredentials mode |
| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
cookieName | string | 'authrim_csrf' | double-submit CSRF Cookie名 |
headerName | string | 'X-Authrim-CSRF' | Cookieプロファイルの状態変更リクエストにコピーするヘッダー名 |
StorageOptions
Section titled “StorageOptions”| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
prefix | string | 'authrim' | ストレージエントリのキープレフィックス |
storage | StorageType | 'memory' | ストレージバックエンド |
| StorageType | 動作 |
|---|---|
'memory' | メモリのみ — ページ更新で消失 |
'sessionStorage' | タブ単位 — タブを閉じるとクリア |
'localStorage' | 永続的 — タブ間で共有 |
コンテキストAPI
Section titled “コンテキストAPI”SDKはSvelteコンテキストを使用して認証クライアントをコンポーネント間で共有します。
コンテキストの設定
Section titled “コンテキストの設定”AuthProvider は内部で setAuthContext(auth) を呼び出します。手動セットアップの場合:
import { setAuthContext } from '@authrim/sveltekit';
// Svelteコンポーネントの初期化内でsetAuthContext(auth);コンテキストの読み取り
Section titled “コンテキストの読み取り”import { getAuthContext, hasAuthContext } from '@authrim/sveltekit';
// 認証クライアントを取得(未設定時はスロー)const auth = getAuthContext();
// コンテキストの存在確認if (hasAuthContext()) { const auth = getAuthContext();}// ✅ 正しい — コンポーネント初期化時に呼び出しconst auth = getAuthContext();
onMount(() => { // ✅ ここでauthを使用 auth.session.get();});
function handleClick() { // ✅ ここでauthを使用 auth.passkey.login();}// ❌ 間違い — onMount内でgetAuthContextonMount(() => { const auth = getAuthContext(); // スロー!});プロバイダー(上級者向け)
Section titled “プロバイダー(上級者向け)”高度なカスタマイズ用に、HTTPクライアント、暗号プロバイダー、ストレージをオーバーライドできます:
import { BrowserHttpClient, BrowserCryptoProvider, createBrowserStorage,} from '@authrim/sveltekit';| プロバイダー | 用途 |
|---|---|
BrowserHttpClient | Authrimサーバーへのリクエスト |
BrowserCryptoProvider | PKCEコード検証子/チャレンジの生成 |
createBrowserStorage() | クライアントサイドストレージの抽象化 |
クリーンアップ
Section titled “クリーンアップ”認証クライアントが不要になったら destroy() でクリーンアップ:
auth.destroy();イベントリスナーを削除し、タイマーをクリアします。AuthProvider はコンポーネント破棄時に自動的に呼び出します。
AuthProvider を使用していない場合は、手動で destroy() を呼び出してください:
<script lang="ts"> import { onDestroy } from 'svelte'; import { getAuthContext } from '@authrim/sveltekit';
const auth = getAuthContext();
onDestroy(() => { auth.destroy(); });</script>TypeScript型
Section titled “TypeScript型”すべての型は @authrim/sveltekit からエクスポートされています:
import type { // 設定 AuthrimConfig, StorageOptions, StorageType,
// クライアント AuthrimClient,
// レスポンス AuthResponse, AuthError, AuthSessionData,
// 名前空間 PasskeyNamespace, EmailCodeNamespace, SocialNamespace, SessionNamespace, ConsentNamespace, DeviceFlowNamespace, CIBANamespace, LoginChallengeNamespace,
// ストア AuthStores, AuthLoadingState,
// イベント AuthEventName, AuthEventPayloads, AuthEventHandler,
// Core再エクスポート Session, User, SocialProvider, PasskeyLoginOptions, PasskeySignUpOptions, PasskeyRegisterOptions, PasskeyCredential, EmailCodeSendOptions, EmailCodeSendResult, EmailCodeVerifyOptions, SocialLoginOptions,} from '@authrim/sveltekit';サーバー型:
import type { ServerAuthContext, ServerSessionManager, ServerSessionManagerOptions, AuthHandleOptions, AuthLoadOptions,} from '@authrim/sveltekit/server';SSR注意事項
Section titled “SSR注意事項”ハイドレーション安全性
Section titled “ハイドレーション安全性”AuthProvider は同期的SSR同期(_syncFromSSR())を使用してハイドレーション不一致を防止します。ストアの値は最初のレンダリング前に設定されるため、$isAuthenticated は最初から正しい値を持ちます。
クライアント専用コード
Section titled “クライアント専用コード”createAuthrim() はブラウザAPI(fetch、crypto、localStorage)を使用します。必ず onMount 内または動的インポートで呼び出してください:
// ✅ 正しい — onMount内onMount(async () => { const { getAuth } = await import('$lib/auth'); auth = await getAuth();});// ❌ 間違い — サーバーでも実行されるimport { getAuth } from '$lib/auth';const auth = await getAuth(); // サーバーで失敗クライアントからアクセス可能な環境変数には PUBLIC_ プレフィックスを使用:
PUBLIC_AUTHRIM_ISSUER=https://auth.example.comPUBLIC_AUTHRIM_CLIENT_ID=my-appクライアントコードでは import.meta.env.PUBLIC_AUTHRIM_ISSUER でアクセス。
Svelte 4互換性
Section titled “Svelte 4互換性”SDKコンポーネントは内部でSvelte 4構文を使用していますが、Svelte 4と5の両方のプロジェクトで動作します。アプリコードの構文マッピング:
| 機能 | Svelte 5(推奨) | Svelte 4 |
|---|---|---|
| Props | let { data } = $props() | export let data |
| State | let count = $state(0) | let count = 0 |
| Derived | const doubled = $derived(count * 2) | $: doubled = count * 2 |
| Effects | $effect(() => { ... }) | $: { ... } |
| イベント(リスン) | onclick={handler} | on:click={handler} |
| イベント(ディスパッチ) | コールバックprops | createEventDispatcher() |
| スロット(デフォルト) | {@render children()} | <slot /> |
| スロット(名前付き) | {#snippet name()}{/snippet} | <div slot="name"> |
| スロットprops | Snippetパラメータ | let:propName |
SDKコンポーネントのイベント
Section titled “SDKコンポーネントのイベント”SDKコンポーネントはSvelte 4の createEventDispatcher でイベントをディスパッチします。Svelte 5プロジェクトでは両方の構文が動作します:
<!-- Svelte 5では両方動作 --><SignInButton on:success={handleSuccess} /><SignInButton onsuccess={handleSuccess} />SDKコンポーネントのスロット
Section titled “SDKコンポーネントのスロット”SDKコンポーネントは <slot> と <slot name="..."> を使用します。Svelte 5プロジェクトでは両方の構文が動作します:
<!-- Svelte 5 snippet構文 --><ProtectedRoute> <p>保護されたコンテンツ</p> {#snippet loading()} <p>読み込み中...</p> {/snippet}</ProtectedRoute>
<!-- Svelte 4 slot構文(Svelte 5でも動作) --><ProtectedRoute> <p>保護されたコンテンツ</p> <p slot="loading">読み込み中...</p></ProtectedRoute>トラブルシューティング
Section titled “トラブルシューティング””getContext must be called during component initialization”
Section titled “”getContext must be called during component initialization””getAuthContext() がコンポーネント初期化外で呼び出されました。<script> ブロックのトップレベルに移動してください。
“Cannot read properties of null (reading ‘passkey’)”
Section titled ““Cannot read properties of null (reading ‘passkey’)””認証クライアントが初期化されていません。AuthProvider がコンポーネントツリーをラップし、レンダリング前にクライアントが作成されていることを確認してください。
ログイン後もストアがnullのまま
Section titled “ログイン後もストアがnullのまま”イベントは自動的にストアを更新します。ストアが更新されない場合:
- 同じ
AuthrimClientインスタンスを使用していることを確認(シングルトンパターン) AuthProviderがコンポーネントツリーのルートにあることを確認- 2つ目のクライアントインスタンスを作成していないことを確認
SSRハイドレーション不一致
Section titled “SSRハイドレーション不一致”AuthProvider に initialSession と initialUser を渡していることを確認:
<AuthProvider {auth} initialSession={data.auth?.session ?? null} initialUser={data.auth?.user ?? null}>ソーシャルログインのコールバックが動作しない
Section titled “ソーシャルログインのコールバックが動作しない”- コールバックURLをAuthrim管理パネルに登録
createAuthHandle()のcallbackPathsにコールバックルートを含める- コールバックページで
auth.social.handleCallback()を呼び出していることを確認
Cookieが設定されない / セッションが失われる
Section titled “Cookieが設定されない / セッションが失われる”createAuthHandle() のオプションを確認:
secure: trueにはHTTPSが必要(ローカル開発ではfalseを使用)sameSite: 'strict'はクロスオリジンリダイレクトをブロック(OAuthフローには'lax'を使用)httpOnly: trueはJavaScriptからのアクセスを防止(推奨)