29. Session Reuse & Global Authentication with storage_state

Global Authentication Pattern in 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!

Task

  • Implement make_auth_context_kwargs(state_file):
  • 1. Return {"storage_state": state_file}
πŸ’‘Common doubts
Did you like the problem?
Lesson 29 of 37
Python
Loading code editor…
Next