Playwright + Python · Lesson 29 of 37

0/37 done

Module 29: Authentication & Sessions

29. Session Reuse & Global Authentication with storage_state

18 minlesson

Your task

Implement make_auth_context_kwargs(state_file):

  1. Return {"storage_state": state_file}

Write it in the editor, then press Check answer (Ctrl + Enter).

Global Authentication Pattern in Python

python
# 1. Login once and save state to disk:
def save_admin_session(browser):
    page = browser.new_page()
    page.goto("https://targetqa.com/login")
    page.get_by_label("Email").fill("admin@targetqa.com")
    page.get_by_label("Password").fill("Secret123")
    page.get_by_role("button", name="Log In").click()
    page.context.storage_state(path="state/admin_auth.json")
    page.close()

# 2. Instantly launch authenticated context:
def test_dashboard_with_saved_auth(browser):
    context = browser.new_context(storage_state="state/admin_auth.json")
    page = context.new_page()
    page.goto("https://targetqa.com/dashboard") # Already authenticated!

Key Takeaways & Walkthrough Summary

Logging in before every single test wastes massive amounts of execution time. In Playwright Python, you log in once, save the session state to a JSON file, and reuse it instantly in subsequent tests. Let's master authentication reuse with storage_state!

Part of the Playwright + Python course (Playwright with Python). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Can I use storage_state with pytest-playwright automatically?

Yes! Add 'pytest --tracing=on --browser-channel=chrome' or pass browser_context_args fixture returning {'storage_state': 'auth.json'}.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip