跳转到主要内容

身份验证

简介

Playwright 在称为浏览器上下文的隔离环境中执行测试。这种隔离模型提高了可重现性并防止了级联测试失败。测试可以加载现有的已认证状态。这消除了在每次测试中进行认证的需要,并加快了测试执行速度。

核心概念

无论您选择哪种身份验证策略,您都可能会将已验证的浏览器状态存储在文件系统上。

我们建议创建 playwright/.auth 目录并将其添加到您的 .gitignore 中。您的认证例程将生成已认证的浏览器状态并将其保存到此 playwright/.auth 目录中的文件中。稍后,测试将重用此状态并以已认证状态开始。

危险

浏览器状态文件可能包含敏感的 cookie 和标头,这些信息可能用于冒充您或您的测试账户。我们强烈不建议将其提交到私有或公共仓库。

mkdir -p playwright/.auth
echo $'\nplaywright/.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 或基于令牌的身份验证,其中身份验证状态存储为cookie本地存储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 的身份验证。很少情况下,会话存储用于存储与登录状态相关的信息。会话存储特定于特定域,并且不会在页面加载之间持久存在。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 + "')");