2023年8月31日 • ☕️ 3 min read

Auth0をカスタマイズしたら、設定がうまくできるかどうか自動テストで確認したいでしょう。ログイン関連がデグレしたらインパクトがデカいからです。MFA(Multi-factor Authentication:多要素認証)のワンタイムパスワード(OTP)を有効にしたら、E2Eテストのハードルがぐんと上がるイメージがありますが、実はそんなに難しいことではありません。今回はPlaywrightでMFA(OTP)有効のログインテストの方法を紹介したいと思います。

Auth0のOTPを有効にする

Security → Multi-factor Authで有効にできます。

auth0-enable-otp.png

そして、テストするためにAdaptive MFAではなく、Always有効にすれば良いでしょう。

auth0-enable-require-mfa.png

OTPのsecretを記録

まずAuth0のAPPを立ち上げてサインアップしましょう。ワンタイムパスワードQRコードが表示されたら Trouble Scanning? をクリックしてください。

otp-register.png

OTPのsecretコードを記録しましょう。

otp-secret.png

ワンタイムパスワードを生成

OTPAuthを使えば簡単にできます。

otp.js
Copy
import * as OTPAuth from "otpauth";

// Create a new TOTP object.
const totp = new OTPAuth.TOTP({
  issuer: "ACME",
  label: "Auth0",
  algorithm: "SHA1",
  digits: 6,
  period: 30,
  secret: "GEQVCOKKHJYSK6BOGEVDW3SWHYQS6Z2K",
});

// Generate a token (returns the current token as a string).
const token = totp.generate();
console.log(token);

それでプリントアウトしたtoken(6桁の数字)をAuth0の登録画面に入力すれば接続は完了となります。その後、同じソースコードでログインできるでしょう。

Playwrightの自動テスト

普通に書けばいいでしょう。

Copy
const { test, expect } = require("@playwright/test");
const OTPAuth = require("otpauth");

test("login with totp", async ({ page }) => {
  await page.goto("http://localhost:3000/");
  await page.getByRole("button", { name: "Log in" }).click();
  await page.getByLabel("Email address").fill("my-email@gmail.com");
  await page.getByLabel("Password").fill("change-to-your-pass-word");
  await page.getByRole("button", { name: "Continue", exact: true }).click();
  await page.getByLabel("Enter your one-time code").fill(getToken());
  await page.getByRole("button", { name: "Continue" }).click();

  await expect(
    page.getByRole("heading", { name: "React.js Sample Project" })
  ).toBeVisible();
});

const getToken = () => {
  const totp = new OTPAuth.TOTP({
    issuer: "ACME",
",
    algorithm: "SHA1",
    digits: 6,
    period: 30,
    secret: "GEQVCOKKHJYSK6BOGEVDW3SWHYQS6Z2K",
  });

  // Generate a token (returns the current token as a string).
  const token = totp.generate();

  return token;
};

E2Eテストを走らせる

playwright-auth0-totp.gif

参考になれれば幸いです。


関連投稿

Playwright+Github Actionでビジュアルリグレッションテストしてみた -- 3

2023年3月19日

ThunderMiracle

Blog part of ThunderMiracle.com