2段階認証のブラウザテスト

作成日:2025-05-13, 更新日:2025-05-13

メモ

2段階認証のブラウザテストをしようと思ったけど、保留
いずれやるかもしれないので、メモだけしておく

用語

  • 2fa(two-factor authentication: 2要素認証、2段階認証)
  • TOTP(Time-based One-Time Password: 時刻ベースのワンタイムパスワード)

ライブラリの追加

> npm install otplib

...「ワンタイムパスワード」のライブラリだから「otp」だよな、きっと

テストソースのサンプル

import { test, expect } from '@playwright/test';
import { authenticator } from 'otplib';

const SECRET = 'KZXW6YTBONFWW3DJ'; // シークレットキー(例)

test('2FA必須ユーザーのログイン', async ({ page }) => {
  await page.goto('https://example.com/login');

  await page.fill('#username', 'testuser');
  await page.fill('#password', 'testpass');
  await page.click('button[type="submit"]');

  // 2FAコードを生成して入力
  const code = authenticator.generate(SECRET);
  await page.fill('#twoFactorCode', code);
  await page.click('button[type="submit"]');

  await expect(page).toHaveURL(/dashboard/);
});