Playwright Authentication and Sessions
Build Playwright authentication tests for login, saved sessions, logout, expiry, and role isolation, then verify the same outcomes through ContextQA MCP.
Quick answer
Test login with a fresh browser context, then verify the authenticated identity and a protected operation. Reuse saved authentication state only for tests whose subject is another feature. Keep accounts and tenant data isolated, test logout and expiry against the server's policy, and verify that denied actions leave protected data unchanged. A visible login screen or hidden button alone cannot prove access control works.
This guide concerns authentication in your application. Connecting a coding agent to ContextQA through MCP has its own authentication workflow; it does not sign the test browser into your application.
Define the session contract first
Before asking Claude Code, Cursor, or Codex to write tests, record the approved environment, identity provider, session mechanism, disposable accounts, roles, tenant IDs, and cleanup procedure. Agree what should happen after idle expiry, absolute expiry, logout, and permission changes. Different products may intentionally have different revocation policies.
Login
Expected identity and tenant; protected operation succeeds
Saved session
Intended account remains valid before feature assertions
Logout
Current browser loses access; old session fails if revocation is required
Expiry
Server rejects the expired session under the documented policy
Wrong role or tenant
Request denied; protected state unchanged
Use an approved test tenant and identity-provider configuration. A staging fixture may provision accounts; it should not silently disable production authentication or bypass SSO/MFA. Keep a separate identity-provider integration test when the provider is part of the behavior being verified.
Separate login coverage from authentication setup
Playwright supports saving authenticated state and loading it into isolated browser contexts. Store any files in an ignored location such as playwright/.auth/; they can contain reusable credentials. Shared accounts suit read-only tests, while tests changing shared server state need isolated accounts or data. See Playwright authentication.
The key testing distinction is the assertion being made. A dashboard test starting with saved state can verify dashboard behavior. It does not demonstrate that today's login form, redirect, or MFA flow works. Preserve a fresh-login test even when other tests reuse authentication.
Cookies, localStorage, and sessionStorage are not interchangeable. Playwright storage snapshots include cookies and localStorage; IndexedDB capture requires its supported option. SessionStorage needs separate handling when your application depends on it. Consult the storage-state API for your installed version rather than copying an unfamiliar token into a different storage mechanism.
Also distinguish browser authentication from API authentication: page.request shares the browser context's cookie jar. It does not automatically turn a localStorage token into a bearer header. A token-based API needs its documented authentication setup. Playwright API request context.
Example: prove login and server-side logout
This is an illustrative application test, not a supplied demo application or a recorded passing run. Adapt these requirements before execution:
Your Playwright configuration supplies an approved
baseURL./loginhasEmail,Password, andSign incontrols; successful login reaches/projects.The application uses cookie-based sessions.
GET /api/sessionreturns 200 withuserId,role, andtenantId; an invalid session returns 401 without redirecting to HTML.Sign outreturns to/loginand revokes the session on the server.The environment supplies a disposable viewer account through the four variables below. No other test changes this account concurrently.
The last assertion distinguishes cookie deletion from server-side revocation. Retain it only when revocation is the agreed requirement; document a different policy explicitly. Never print the captured state. Review traces and request artifacts for credentials before sharing them.
Add expiry and authorization cases
Use an approved short-lived test session or server-side test-clock control for expiry. Advancing only the browser's clock may change a countdown while leaving the server session valid. Deleting a browser cookie tests missing authentication, not natural server-side expiry.
For authorization, prepare separate viewer, editor, and other-tenant fixtures. Start each in a separate browser context and verify identity before the protected action. Try the forbidden operation through its documented API as well as checking the UI. Compare the protected record before and after the attempt using an authorized observer. A hidden edit button does not establish that the write endpoint rejects a viewer.
Use this bounded coding-agent prompt:
For a controlled negative check, introduce an isolated test-build defect such as omitting session revocation, then confirm the revocation assertion fails. Restore the build and rerun. A syntax error or unreachable identity provider is not the expected failure.
Cover the managed workflow with ContextQA MCP
Connect ContextQA MCP, inspect its current tools, and search for matching cases before creating duplicates. Use the documented authentication workflow patterns and reusable prerequisites for ordinary feature tests. Keep the actual login/logout test independent of a prerequisite that skips login.
Ask the agent to prepare separate managed cases for valid login, logout, and the approved expiry/denial scenarios. Supply the acceptance matrix and reference configured secrets rather than their values. Review generated steps for identity checks, exact denials, and unchanged state before execution. Where a server-side revocation check requires a companion API test, record that dependency instead of declaring the browser steps sufficient.
Retrieve the terminal result and available step evidence using the execution reference. A failed prerequisite leaves the protected workflow unverified. A correctly denied operation is a passing negative test.
Frequently asked questions
Why does saved authentication work locally but fail in CI?
Check expiry, environment hostname, cookie domain, role, identity-provider policy, and fixture ownership. Recreate the session for the intended environment. Do not solve a wrong account by removing identity assertions.
Can I reuse one administrator session for every test?
That can conceal permission defects and create shared-state interference. Use the least-privileged role required by each case and isolate mutable data. Keep role-denial tests separate from successful administrator workflows.
Does a login redirect prove logout worked?
No. Verify the protected operation fails afterward. Where your policy requires revocation, also check the previously issued session, as the example demonstrates.
Next step
Extend the Playwright testing guide with your session contract, or book an authentication workflow demo using one representative test environment.
Official references reviewed September 25, 2026. Recheck client APIs, application policy, and identity-provider behavior when those dependencies change.
Last updated
Was this helpful?
