Playwright + Java · Lesson 30 of 38
Module 30: Authentication & Sessions
Your task
Implement createAuthenticatedContext:
Write it in the editor, then press Check answer (Ctrl + Enter).
import java.nio.file.Paths;
// Step 1: Perform login once and save session state
Page loginPage = browser.newPage();
loginPage.navigate("https://targetqa.com/login");
loginPage.getByLabel("Email").fill("admin@targetqa.com");
loginPage.getByLabel("Password").fill("Secret123!");
loginPage.getByRole(AriaRole.BUTTON).click();
// Save cookies and localStorage to auth.json:
loginPage.context().storageState(new BrowserContext.StorageStateOptions()
.setPath(Paths.get("state/adminAuth.json")));
// Step 2: Instantly spawn pre-authenticated contexts:
BrowserContext authenticatedContext = browser.newContext(
new Browser.NewContextOptions().setStorageStatePath(Paths.get("state/adminAuth.json"))
);
Page authPage = authenticatedContext.newPage();
authPage.navigate("https://targetqa.com/dashboard"); // Already logged in!Logging in via the UI before every single test wastes tremendous amounts of time. In Playwright, you log in once, save the browser's storage state to a JSON file, and reload it directly in new contexts. Let's master session reuse with storageState!
Part of the Playwright + Java course (Playwright with Java). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.
Playwright captures all cookies, JWT tokens, and localStorage items associated with the session, allowing instant authentication bypass.
Ready? Solve the task in the editor
Use Check answer to mark it complete. Hints are there if you need them.
___