
パスキー(WebAuthn)を使うログイン
パスキー(WebAuthn)を使うログインは、E2Eテストで扱いにくい部類です。
通常のユーザー名とパスワードを入力してログインするページであれば、以下のように入力してログインボタンを押すだけですが、パスキーはそんなに単純ではありません。
await page.locator('#username').fill(username)
await page.locator('#password').fill(password)
await page.getByRole('button', { name: 'ログイン' }).click()生体認証やセキュリティキーのダイアログは、ブラウザ自動化から操作できません。
しかし、Chromiumには仮想オーセンティケーターがあるため、この問題を解決できます。
1. 仮想オーセンティケーターを追加する
Chrome DevTools Protocol(CDP)の WebAuthn ドメインでソフトウェア上の認証器を作れるため、そこからパスキーの作成と署名を自動で処理できます。
import { test, expect, type Page, type CDPSession } from '@playwright/test'
async function addVirtualAuthenticator(page: Page) {
const client = await page.context().newCDPSession(page)
await client.send('WebAuthn.enable')
const { authenticatorId } = await client.send(
'WebAuthn.addVirtualAuthenticator',
{
options: {
protocol: 'ctap2',
transport: 'internal', // プラットフォーム認証器(Touch IDなど)相当
hasResidentKey: true, // パスキー(discoverable credential)に必須
hasUserVerification: true, // 認証器がユーザー検証に対応しているものとして振る舞う
isUserVerified: true, // 生体認証が成功した状態にする
automaticPresenceSimulation: true, // ユーザー操作を自動で行う
},
},
)
return { client, authenticatorId }
}2. パスキーを登録する
登録の前に、必ず仮想オーセンティケーターを追加します。
test('パスキーを登録する', async ({ page }) => {
await addVirtualAuthenticator(page)
// 事前にパスワード等でログインしておく
await page.goto('https://example.com/login')
await page.getByLabel('メールアドレス').fill(process.env.E2E_USER!)
await page.getByLabel('パスワード').fill(process.env.E2E_PASSWORD!)
await page.getByRole('button', { name: 'ログイン' }).click()
// パスキー登録
await page.goto('https://example.com/settings/security')
await page.getByRole('button', { name: 'パスキーを追加' }).click()
await expect(page.getByText('パスキーを登録しました')).toBeVisible()
})3. パスキーでログインする
登録と同じテスト内なら、同じ認証器のまま続けてログインできます。
test('パスワードなしでパスキーログイン', async ({ page }) => {
await addVirtualAuthenticator(page)
// ... 登録処理(上記)の後に ...
// ログアウトして、ログイン画面に戻る
await page.getByRole('button', { name: 'ログアウト' }).click();
await page.goto('https://example.com/login')
// パスワードは入力しない
await page.getByRole('button', { name: 'パスキーでログイン' }).click()
await expect(page).toHaveURL(/dashboard/)
});
4. 登録済みパスキーをテスト間で再利用する
仮想オーセンティケーターはブラウザコンテキストごとに作られ、終了すると消えます。
テストのたびに登録すると遅く不安定になります。そこで、一度登録した資格情報を取り出して保存し、次回以降に注入します。
資格情報をエクスポートする
import fs from 'node:fs'
async function exportCredentials(client: CDPSession, authenticatorId: string) {
const { credentials } = await client.send('WebAuthn.getCredentials', {
authenticatorId,
})
fs.writeFileSync('.auth/passkey.json', JSON.stringify(credentials, null, 2))
}passkey.jsonはPlaywrightで初回ログイン時に保存した情報です。
.auth/passkey.json
[
{
"credentialId": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"isResidentCredential": true,
"rpId": "your-tenant.us.auth0.com",
"privateKey": "BASE64_ENCODED_PKCS8_PRIVATE_KEY_DUMMY",
"userHandle": "BASE64_ENCODED_USER_HANDLE_DUMMY",
"signCount": 1,
"backupEligibility": false,
"backupState": false,
"userName": "user@example.com",
"userDisplayName": "user@example.com"
}
]
資格情報をインポートする
async function importCredentials(client: CDPSession, authenticatorId: string) {
const credentials = JSON.parse(fs.readFileSync('.auth/passkey.json', 'utf-8'))
for (const credential of credentials) {
await client.send('WebAuthn.addCredential', { authenticatorId, credential })
}
}これで、各テストは登録済みのパスキーを持った状態で始まります。
5. ログイン状態の再利用(storageState)
パスキーログインを全テストで毎回行う必要はありません。
セットアップ用のプロジェクトで一度ログインし、storageState を保存すると、後続のテストはログイン済みで始まります。
fixtures.ts
import { test as base } from '@playwright/test'
export const test = base.extend({
page: async ({ page }, use) => {
const { client, authenticatorId } = await addVirtualAuthenticator(page)
await importCredentials(client, authenticatorId)
await use(page)
},
})auth.setup.ts
import { test as setup } from './fixtures'
setup('authenticate with passkey', async ({ page }) => {
await page.goto('https://example.com/login')
await page.getByRole('button', { name: 'パスキーでログイン' }).click()
await page.waitForURL(/dashboard/)
await page.context().storageState({ path: '.auth/state.json' })
})playwright.config.ts
import { defineConfig } from '@playwright/test'
export default defineConfig({
projects: [
{ name: 'setup', testMatch: /auth\.setup\.ts/ },
{
name: 'chromium',
use: { browserName: 'chromium', storageState: '.auth/state.json' },
dependencies: ['setup'],
},
],
})パスキーのログイン動作そのものは、専用のテスト1本で検証します。
ほかのテストはstorageStateを使うと、実行時間を短くできます。
まとめ
- PlaywrightはnewCDPSessionとWebAuthn.addVirtualAuthenticatorで、パスキーを自動操作できます。
- 登録とログインは、ダイアログなしで完結します。
- getCredentialsとaddCredentialで資格情報を保存・復元すると、テストを安定させ高速化できます。
- 保存した資格情報には秘密鍵が含まれるため、テスト専用アカウントに限定し、Gitに含めないでください。



