Authentication
Relevant source files
The following files were used as context for generating this wiki page:
Playwright provides robust mechanisms to handle authentication, enabling fast and reliable tests by isolating authentication logic from test logic. The primary strategy is to "log in once" by saving the authentication state of a browser context and reusing it across multiple tests. This bypasses repetitive login operations, significantly speeding up test suite execution while maintaining full test isolation.
The two main approaches for handling authentication are:
- Storage State: For cookie-based or
localStorage-based authentication, you can save the state of an authenticated context (cookies andlocalStorage) into a file and then create new contexts with that state. This is the most common and recommended approach. - HTTP Credentials: For sites using HTTP Basic Authentication, you can provide credentials that will be automatically sent with requests.
This document details these authentication strategies and how to implement them within the Playwright Test framework.
Sources: README.md:83-85, packages/playwright/types/test.d.ts:2100-2121, 2152-2166
Storage State for Session-Based Authentication
The storageState feature is the cornerstone of authentication management in Playwright. It allows you to capture cookies and localStorage from a browser context and reuse them, effectively preserving a logged-in session.
What is Storage State?
Storage state is an object containing the browser's cookies and localStorage for various origins. It can be retrieved from an authenticated context and then used to initialize new contexts.
The diagram below shows the structure of the storageState object.
This diagram illustrates the data structure for storageState, which includes cookies and localStorage entries keyed by origin.
Sources: packages/playwright/types/test.d.ts:2100-2121, utils/generate_types/test/test.ts:182-191
Global Setup for Authentication
The recommended pattern for managing authentication is to use a globalSetup file in your Playwright configuration. This setup file runs once before all tests, performs the login, and saves the storageState to a file. Subsequent tests then use this file to start in an authenticated state.
The Authentication Flow
The following sequence diagram illustrates the globalSetup authentication flow.
This diagram shows how globalSetup authenticates and saves the state, which is then used by the test runner to initialize test pages in a logged-in state.
Sources: tests/playwright-test/global-setup.spec.ts:289-328
Configuration Example
To implement this, you configure globalSetup and use.storageState in playwright.config.ts.
playwright.config.ts
// playwright.config.ts
import { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
// Path to the global setup file.
globalSetup: require.resolve('./auth'),
use: {
// All tests will load this state.
storageState: 'state.json',
},
};
export default config;
Sources: tests/playwright-test/global-setup.spec.ts:290-300
auth.ts (Global Setup File)
// auth.ts
import { chromium, FullConfig } from '@playwright/test';
async function globalSetup(config: FullConfig) {
const { baseURL, storageState } = config.projects[0].use;
const browser = await chromium.launch();
const page = await browser.newPage();
// Navigate and perform login actions
await page.goto(baseURL!);
await page.evaluate(() => {
localStorage['name'] = 'value';
});
// Save authentication state to a file
await page.context().storageState({ path: storageState as string });
await browser.close();
};
export default globalSetup;
This setup script launches a browser, navigates to the login page, simulates user login (in this case, by setting a localStorage item), and saves the resulting cookies and localStorage to the path specified in storageState.
Sources: tests/playwright-test/global-setup.spec.ts:301-317
HTTP Basic Authentication
For applications that use HTTP Basic Authentication, Playwright provides the httpCredentials option. This can be configured globally in playwright.config.ts or on a per-context/per-request basis.
Configuration
You can set httpCredentials in the use section of your playwright.config.ts.
| Property | Type | Description - |
|---|---|---|
username | string | The username for authentication. - |
password | string | The password for authentication. - |
origin | string | (Optional) An origin to which the credentials should be sent. If not specified, credentials are sent to any server upon an unauthorized response. - |
send | string | (Optional) When to send the credentials. Can be set to 'always' to preemptively send the Authorization header without waiting for a 401 challenge. - |
Sources: packages/playwright/types/test.d.ts:2152-2166, tests/library/global-fetch.spec.ts:100-104, tests/library/browsercontext-fetch.spec.ts:365-385
Usage Example
The httpCredentials option can be set when creating a new context or page.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
httpCredentials: {
username: 'user',
password: 'password',
},
},
});
This configuration will automatically handle WWW-Authenticate: Basic challenges from any origin.
Sources: packages/playwright/types/test.d.ts:2152-2166, tests/library/global-fetch.spec.ts:100-104
You can also scope credentials to a specific origin:
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
httpCredentials: {
username: 'user',
password: 'password',
origin: 'https://api.example.com'
},
},
});
Sources: tests/library/global-fetch.spec.ts:120-125
Authentication in HAR Recordings
When recording HAR files, Playwright correctly captures authentication-related information.
- Request Cookies: Cookies sent with a request, including session cookies from
storageState, are recorded in therequest.cookiesarray of the HAR entry. - Set-Cookie Headers:
Set-Cookieheaders from responses are parsed and stored in theresponse.cookiesarray. - Authentication Headers: For HTTP Basic Auth, the
Authorizationheader is included in the request headers.
This ensures that HAR files provide a complete picture of the authentication exchanges during a test session.
Sources: tests/library/har.spec.ts:175-187, 189-200, tests/library/browsercontext-fetch.spec.ts:352-363
Conclusion
Playwright's authentication features are designed to make tests faster and more maintainable by separating authentication logic from test steps. By using storageState with globalSetup, you can create a highly efficient testing workflow that logs in only once for the entire suite. For simpler use cases like HTTP Basic Auth, the httpCredentials option provides a straightforward configuration. These tools, combined with full test isolation, allow for the creation of robust and scalable end-to-end test suites.