12k
All articles

Testing a Passkey Login Flow with Playwright

Test passkey sign-up and sign-in in CI with Playwright virtual WebAuthn credentials. Capture and seed passkeys, check failure paths, and migrate from CDP.

OpenReplay Team
OpenReplay Team
Testing a Passkey Login Flow with Playwright

Playwright 1.61 added a virtual WebAuthn authenticator, browserContext.credentials, which answers navigator.credentials.create() and navigator.credentials.get() inside the page, so you can test passkey sign-up and sign-in in CI without a fingerprint reader or a hardware security key.

Your app ships passkey login, and the end-to-end suite stops at the “Create a passkey” button because the CI runner has no authenticator to answer it. This guide fills that gap for an existing suite. You register through the real sign-up UI once, capture the passkey to a file, seed it into later tests, cover the failure paths, and remove any old Chromium-only setup. The examples need Playwright 1.61 or later. If you’re new to the runner, start with getting started with UI testing in Playwright.

Key Takeaways

  • Call context.credentials.install() before the page first touches navigator.credentials. If you seed credentials but never install the authenticator, the page never sees them.
  • context.credentials.get({ rpId }) returns every credential for that relying party, including passkeys the page registered itself, and includes each one’s private key.
  • A captured passkey file contains a working private key. Write it to a git-ignored directory and regenerate it in a setup project on every run.
  • The Credentials API has no documented way to simulate a cancelled prompt or failed biometric check, so native prompts and account pickers still need manual testing on real devices.
  • According to the 1.61 release notes, the Credentials API works in all browsers, so it can take over from Chromium-only CDP virtual authenticators.

Why Do Passkey Tests Fail in CI?

Passkey tests fail in CI because a passkey ceremony needs an authenticator: a platform authenticator such as Touch ID or Windows Hello, or a roaming key such as a YubiKey. A headless CI runner has neither, so the browser has nothing that can answer the WebAuthn call. Mocking navigator.credentials gets the button click to pass, but no real signature ever reaches your server, so the test proves nothing about authentication. Playwright 1.61 closes this gap with a software authenticator that creates real key pairs and signs real assertions.

How Do the WebAuthn Ceremonies Work?

Passkey login uses two ceremonies. At sign-up, the app calls navigator.credentials.create(). The authenticator generates a key pair, keeps the private key, and returns the public key for the server to store. At sign-in, the app calls navigator.credentials.get() with a server challenge. The authenticator signs the challenge, and the server checks the signature against the stored public key. For background on why apps are moving this way, see passwords or passkeys.

Both ceremonies are tied to a relying party ID (rpId), which is normally your registrable domain. The WebAuthn Level 3 specification states that an RP ID determines the scope of a credential, and it requires the authenticator to check that the requested RP ID exactly matches the credential’s rpId. In local runs the rpId is usually localhost.

Install the Virtual Authenticator Before Navigation

Call context.credentials.install() before navigating to any page that uses WebAuthn. The install step overrides create() and get() in every current and future page of the context. If you seed a credential and skip install(), the credential sits in the authenticator and the page never sees it.

MethodPurposeAdded
install()Routes the page’s WebAuthn calls to the virtual authenticator1.61
create(rpId, options?)Seeds a credential, either generated or imported1.61 (signCount in 1.64)
get({ id?, rpId? })Lists credentials, including private keys1.61
delete(id)Removes a seeded or page-registered credential1.61

Capture a Playwright Passkey in a Setup Project

To capture a Playwright passkey, register through your app’s real sign-up flow once per run. Then read the credential back with credentials.get({ rpId }) and write it to disk. This is the same capture-and-reuse pattern the docs show. A setup project with dependencies makes it run before every browser project:

// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  use: { baseURL: 'http://localhost:3000' },
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    { name: 'chromium', use: { ...devices['Desktop Chrome'] }, dependencies: ['setup'] },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] }, dependencies: ['setup'] },
    { name: 'webkit', use: { ...devices['Desktop Safari'] }, dependencies: ['setup'] },
  ],
});
// tests/paths.ts
export const PASSKEY_FILE = 'playwright/.auth/passkey.json';
export const RP_ID = 'localhost';
// tests/passkey.setup.ts
import { test as setup, expect } from '@playwright/test';
import fs from 'node:fs';
import path from 'node:path';
import { PASSKEY_FILE, RP_ID } from './paths';

setup('register a passkey', async ({ context, page }) => {
  await context.credentials.install(); // before the first navigation
  await page.goto('/signup');
  await page.getByLabel('Email').fill(`passkey-${Date.now()}@example.test`);
  await page.getByRole('button', { name: 'Create a passkey' }).click();
  await expect(page.getByText('Passkey created')).toBeVisible();

  await expect
    .poll(async () => (await context.credentials.get({ rpId: RP_ID })).length)
    .toBe(1);
  const [credential] = await context.credentials.get({ rpId: RP_ID });

  fs.mkdirSync(path.dirname(PASSKEY_FILE), { recursive: true });
  fs.writeFileSync(PASSKEY_FILE, JSON.stringify(credential));
});

The selectors are placeholders, so swap in your own. The test checks two separate things. The UI assertion shows that the server accepted the registration, and the authenticator poll shows that the key exists. If your sign-in asks for the username first, save the email alongside the credential. The constants live in paths.ts so that spec files never import from a setup file.

The captured file contains a working private key, so treat it as a test secret:

# .gitignore
playwright/.auth/

Don’t commit the file. Regenerate it on every run. It only works while your backend still holds the matching public key, so a database reset invalidates it. The RP_ID must also match the host your tests visit. If environments run on different hosts, derive it from baseURL.

Seed the Passkey and Sign In

Before the page exists, load the captured credential with credentials.create(credential.rpId, credential) and call install(). Overriding the built-in context fixture handles the ordering, because the fixture runs before the test creates its page.

// tests/fixtures.ts
import { test as base } from '@playwright/test';
import fs from 'node:fs';
import { PASSKEY_FILE } from './paths';

export const test = base.extend({
  context: async ({ context }, use) => {
    const credential = JSON.parse(fs.readFileSync(PASSKEY_FILE, 'utf8'));
    await context.credentials.create(credential.rpId, credential);
    await context.credentials.install();
    await use(context);
  },
});
export { expect } from '@playwright/test';
// tests/signin.spec.ts
import { test, expect } from './fixtures';

test('signs in with a passkey', async ({ page }) => {
  await page.goto('/login');
  await page.getByRole('button', { name: 'Sign in with a passkey' }).click();
  await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
});

Seeded credentials are discoverable ECDSA P-256 keys, so the same passkey covers both username-first and usernameless sign-in. The WebAuthn signature counter can cause trouble on the server. The WebAuthn spec treats a signature counter that does not increase as a sign of a possibly cloned authenticator. If your server enforces that check, tests that reuse one captured file can be rejected. You can fix this by creating a fresh user per run, or by passing signCount to create(). That option arrived in Playwright 1.64 and lets the credential continue from the counter your relying party has already seen.

From 1.62, browserContext.storageState() also accepts credentials: true, so passkeys can be saved in a storage-state file next to your cookies:

await context.storageState({ path: 'playwright/.auth/state.json', credentials: true });

Test the Failure Paths

Use credentials.delete(id) to test what a user sees when the device has no passkey. Then assert your app’s own fallback UI:

test('shows a fallback when this device has no passkey', async ({ context, page }) => {
  const [credential] = await context.credentials.get();
  await context.credentials.delete(credential.id);
  await page.goto('/login');
  await page.getByRole('button', { name: 'Sign in with a passkey' }).click();
  await expect(page.getByText('No passkey found')).toBeVisible();
});

For a wrong-domain case, import test from @playwright/test instead of the fixture. Seed the captured keys under a different relying party, such as create('other.example', keys), then call install(). Because the spec scopes a credential to its RP ID, your login page should behave as if no passkey exists.

Assert only the message your app shows. The docs don’t say how the page’s get() call settles when no credential matches, so don’t assert an error name. You may also need to adjust the assertion timeout to match how long your app waits before showing its fallback.

Playwright’s Credentials API has no documented switch for a cancelled prompt or failed user verification. Native OS prompts, account pickers, QR-based cross-device sign-in and passkey sync still need manual testing on real devices.

Migrate from CDP Virtual Authenticators

If you set up passkey tests with CDP’s WebAuthn.addVirtualAuthenticator, replace that setup with context.credentials and you also get Firefox and WebKit coverage. CDP is a Chromium protocol, while the 1.61 release notes say the Credentials API works in all browsers.

  1. Delete the newCDPSession setup and the authenticator ID handling that goes with it.
  2. Replace them with install(), plus create() wherever you seeded keys.
  3. Swap CDP credential reads for get(), and swap removals for delete(id).
  4. Remove any test.skip guards that limit passkey specs to Chromium.
  5. Retire tests that depend on CDP-only toggles such as user-verification overrides. They have no documented equivalent, so move those checks to manual testing.

Next Step

Testing passkeys in CI comes down to install, capture, seed and assert, all through one Playwright API that runs in every engine. Start by adding the setup project and .gitignore entry above. Then point the sign-in spec at your real login page and run it across all three browser projects.

FAQs

Do I need to call install() when restoring passkeys from a storage-state file?

No. Restoring a storage state that contains credentials, through the storageState option or browserContext.setStorageState(), installs the virtual WebAuthn authenticator automatically, with the same effect as credentials.install(). It also stops every real authenticator from working in that context. The saved credentials carry their private keys and signature counters, so keep the file in a git-ignored directory like any other captured passkey.

How do I seed a passkey my backend provisioned instead of registering through the UI?

Pass all four of id, userHandle, privateKey and publicKey to context.credentials.create(rpId, options), then call install(). The private key must be base64url-encoded PKCS#8 DER and the public key base64url-encoded SPKI DER. Calling create() with only an rpId generates a new key pair that your server has no record of.

How can I test that my server handles the WebAuthn signature counter?

Use the signCount option on credentials.create(), added in Playwright 1.64, to set the credential's starting counter. The first assertion the virtual authenticator signs then reports signCount plus one. Both create() and get() return the current signCount, so call get() after sign-in to confirm the counter advanced. Storage state saves and restores the counter along with the credentials.

Is browserContext.credentials available in Playwright for Python and Java?

Yes. The Python and Java Playwright docs include the Credentials class with the same install, create, get and delete methods as Node.js. Python uses snake_case arguments such as rp_id, user_handle and private_key. Java gets the class through context.credentials() and sets import options with Credentials.CreateOptions builder methods such as setUserHandle() and setPrivateKey().

DevTools for the frontend

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs, track slowdowns and uncover frustrations in your app. Get complete visibility into your frontend with OpenReplay — the most advanced open-source session replay tool for developers.

Star on GitHub12k

We use cookies to improve your experience. By using our site, you accept cookies.