身份验证
简介
Playwright 在称为浏览器上下文 (browser contexts) 的隔离环境中执行测试。这种隔离模型提高了可重复性并防止了连锁测试失败。测试可以加载现有的已验证身份的状态。这消除了在每个测试中进行身份验证的需要,并加快了测试执行速度。
核心概念
无论您选择哪种身份验证策略,您都可能会将已验证的浏览器状态存储在文件系统上。
我们建议创建 playwright/.auth 目录并将其添加到您的 .gitignore 中。 您的身份验证例程将生成经过身份验证的浏览器状态,并将其保存到此 playwright/.auth 目录中的文件中。 之后,测试将重用此状态并以已通过身份验证的方式启动。
浏览器状态文件可能包含敏感的 cookie 和标头,这些信息可能用于冒充您或您的测试账户。我们强烈不建议将其提交到私有或公共仓库。
- Bash
- PowerShell
- 批处理
mkdir -p playwright/.auth
echo $'\nplaywright/.auth' >> .gitignore
New-Item -ItemType Directory -Force -Path playwright\.auth
Add-Content -path .gitignore "`r`nplaywright/.auth"
md playwright\.auth
echo. >> .gitignore
echo "playwright/.auth" >> .gitignore
每次测试前登录
Playwright API 可以自动化交互登录表单。
以下示例登录 GitHub。一旦执行这些步骤,浏览器上下文将进行身份验证。
var page = await context.NewPageAsync();
await page.GotoAsync("https://github.com/login");
// Interact with login form
await page.GetByLabel("Username or email address").FillAsync("username");
await page.GetByLabel("Password").FillAsync("password");
await page.GetByRole(AriaRole.Button, new() { Name = "Sign in" }).ClickAsync();
// Continue with the test
每次测试都重新登录会降低测试执行速度。为了缓解这种情况,请改为重用现有的身份验证状态。
重用已登录状态
Playwright 提供了一种在测试中重用已登录状态的方法。这样,您只需登录一次,然后即可跳过所有测试的登录步骤。
Web 应用程序使用基于 Cookie 或基于令牌的身份验证,其中已验证的身份状态存储为 Cookies、本地存储 (local storage) 或 IndexedDB。Playwright 提供了 BrowserContext.StorageStateAsync() 方法,该方法可用于从已验证的上下文中检索存储状态,然后创建带有预填充状态的新上下文。
Cookie、本地存储和 IndexedDB 状态可以在不同的浏览器中共享。它们取决于您的应用程序的身份验证模型,可能需要 cookie、本地存储或 IndexedDB 的某种组合。
以下代码片段从已验证的上下文中检索状态并使用该状态创建新的上下文。
// Save storage state into the file.
// Tests are executed in <TestProject>\bin\Debug\netX.0\ therefore relative path is used to reference playwright/.auth created in project root
await context.StorageStateAsync(new()
{
Path = "../../../playwright/.auth/state.json"
});
// Create a new context with the saved storage state.
var context = await browser.NewContextAsync(new()
{
StorageStatePath = "../../../playwright/.auth/state.json"
});
高级场景
会话存储
重用经过身份验证的状态涵盖cookie、本地存储和IndexedDB 身份验证。 很少使用 session storage 来存储与登录状态相关的信息。 会话存储特定于特定域,不会在页面加载之间持久化。 Playwright 不提供持久化会话存储的 API,但可以使用以下代码片段来保存/加载会话存储。
// Get session storage and store as env variable
var sessionStorage = await page.EvaluateAsync<string>("() => JSON.stringify(sessionStorage)");
Environment.SetEnvironmentVariable("SESSION_STORAGE", sessionStorage);
// Set session storage in a new context
var loadedSessionStorage = Environment.GetEnvironmentVariable("SESSION_STORAGE");
await context.AddInitScriptAsync(@"(storage => {
if (window.location.hostname === 'example.com') {
const entries = JSON.parse(storage);
for (const [key, value] of Object.entries(entries)) {
window.sessionStorage.setItem(key, value);
}
}
})('" + loadedSessionStorage + "')");