Skip to main content

Authentication

Playwright can be used to automate scenarios that require authentication.

Tests written with Playwright execute in isolated clean-slate environments called browser contexts. This isolation model improves reproducibility and prevents cascading test failures. New browser contexts can load existing authentication state. This eliminates the need to login in every context and speeds up test execution.

Note: This guide covers cookie/token-based authentication (logging in via the app UI). For HTTP authentication use Browser.newContext([options]).

Automate logging in

The Playwright API can automate interaction from a login form.

The following example automates logging into GitHub. Once these steps are executed, the browser context will be authenticated.

Page page = context.newPage();
page.navigate("https://github.com/login");
// Interact with login form
page.locator("text=Login").click();
page.locator("input[name='login']").fill(USERNAME);
page.locator("input[name='password']").fill(PASSWORD);
page.locator("text=Submit").click();
// Continue with the test

Redoing login for every test can slow down test execution. To mitigate that, reuse existing authentication state instead.

Reuse signed in state

Playwright provides a way to reuse the signed-in state in the tests. That way you can log in only once and then skip the log in step for all of the tests.

Web apps use cookie-based or token-based authentication, where authenticated state is stored as cookies or in local storage. Playwright provides browserContext.storageState([options]) method that can be used to retrieve storage state from authenticated contexts and then create new contexts with prepopulated state.

Cookies and local storage state can be used across different browsers. They depend on your application's authentication model: some apps might require both cookies and local storage.

The following code snippet retrieves state from an authenticated context and creates a new context with that state.

// Save storage state into the file.
context.storageState(new BrowserContext.StorageStateOptions().setPath(Paths.get("state.json")));

// Create a new context with the saved storage state.
BrowserContext context = browser.newContext(
new Browser.NewContextOptions().setStorageStatePath(Paths.get("state.json")));

Session storage

Rarely, session storage is used for storing information associated with the logged-in state. Session storage is specific to a particular domain and is not persisted across page loads. Playwright does not provide API to persist session storage, but the following snippet can be used to save/load session storage.

// Get session storage and store as env variable
String sessionStorage = (String) page.evaluate("JSON.stringify(sessionStorage)");
System.getenv().put("SESSION_STORAGE", sessionStorage);

// Set session storage in a new context
String sessionStorage = System.getenv("SESSION_STORAGE");
context.addInitScript("(storage => {\n" +
" if (window.location.hostname === 'example.com') {\n" +
" const entries = JSON.parse(storage);\n" +
" for (const [key, value] of Object.entries(entries)) {\n" +
" window.sessionStorage.setItem(key, value);\n" +
" };\n" +
" }\n" +
"})('" + sessionStorage + "')");

Multi-factor authentication

Accounts with multi-factor authentication (MFA) cannot be fully automated, and need manual intervention. Persistent authentication can be used to partially automate MFA scenarios.

Persistent authentication

Note that persistent authentication is not suited for CI environments since it relies on a disk location. User data directories are specific to browser types and cannot be shared across browser types.

User data directories can be used with the BrowserType.launchPersistentContext(userDataDir[, options]) API.

import com.microsoft.playwright.*;

public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
Path userDataDir = Paths.get("/path/to/directory");
BrowserContext context = chromium.launchPersistentContext(userDataDir,
new BrowserType.LaunchPersistentContextOptions().setHeadless(false));
// Execute login steps manually in the browser window
}
}
}

Lifecycle

  1. Create a user data directory on disk.
  2. Launch a persistent context with the user data directory and login the MFA account.
  3. Reuse user data directory to run automation scenarios.