如何测试魔法链接登录
魔法链接去掉了密码,却把全部登录安全都放进了一封邮件。这封邮件值得认真测试。
要检查什么
- 邮件能到达,而且很快,送到请求它的地址。
- 链接指向当前环境正确的域名。
- 它能让用户登录并进入正确的页面。
- 只能用一次。再次打开不应再次登录。
- 会过期。旧链接会被拒绝,并给出清楚的提示和获取新链接的方法。
- 新链接会替代旧链接,如果你是这样设计的。
Playwright 示例
使用 Playwright 中的邮件验证里的辅助函数(createInbox、waitForEmail、extractLink):
import { test, expect } from '@playwright/test';
import { createInbox, waitForEmail, extractLink } from './helpers/inbox';
test('magic link signs in once', async ({ page, browser }) => {
test.setTimeout(90_000);
const inbox = await createInbox();
await page.goto('/login');
await page.getByLabel('Email').fill(inbox.address);
await page.getByRole('button', { name: 'Email me a link' }).click();
const email = await waitForEmail(inbox.local, { subject: 'Sign in' });
const link = extractLink(email, /\/auth\/magic/);
expect(new URL(link).host).toBe(new URL(page.url()).host);
await page.goto(link);
await expect(page.getByText('Dashboard')).toBeVisible();
// a second use, in a fresh browser, must not work
const other = await (await browser.newContext()).newPage();
await other.goto(link);
await expect(other.getByText(/expired|already used/i)).toBeVisible();
});测试过期
在测试里等 15 分钟太慢了。更好的办法:在测试环境中设置很短的有效期,或者提供一个只在测试中可用、让令牌“变老”的接口。如果可以,保留一个每晚运行、使用真实有效期的慢测试。
当心链接扫描器
有些公司的邮件系统会打开链接进行扫描,这可能在用户点击之前就用掉了一次性链接。常见的解决办法是:先显示一个带“登录”按钮的确认页面,而不是在第一次 GET 时就登录。
想让 AI 智能体来做这些检查?参见用 AI 智能体测试魔法链接。
相关指南
现在就试:上面的免费接口无需注册,文档在临时邮箱 API 页面。如需私有邮箱、webhook 和大规模 CI,QuickInbox Business API 提供每月 5,000 封邮件的免费套餐。