Authentication Testing with JWT in Playwright
Authentication Testing with JWT in Playwright
JWT (JSON Web Tokens) are widely used for stateless authentication in modern web apps. When testing applications that use JWT for authentication, Playwright offers tools to simulate login flows or directly inject JWT tokens to bypass the UI login process.
This guide walks you through both approaches using Playwright (with JavaScript/TypeScript or Python).
✅ What You'll Learn
How JWT-based authentication works
How to authenticate with JWT using Playwright
How to persist authentication for faster testing
1. Understanding JWT Authentication
In a typical JWT auth flow:
User logs in via a form
Backend responds with a JWT token
The token is saved in localStorage or a cookie
All future requests include the JWT (usually in the Authorization header or cookie)
2. Method 1: UI Login + Persist Auth (Best for End-to-End Testing)
๐ง Step-by-Step (JavaScript/TypeScript)
ts
Copy
Edit
// login.spec.ts
import { test, expect } from '@playwright/test';
test('Login and save state', async ({ page }) => {
await page.goto('https://your-app.com/login');
await page.fill('#username', 'testuser');
await page.fill('#password', 'password123');
await page.click('button[type="submit"]');
await page.waitForURL('**/dashboard'); // wait for navigation after login
// Save authentication state to a file
await page.context().storageState({ path: 'auth.json' });
});
✅ Reuse Auth State in Other Tests
ts
Copy
Edit
test.use({ storageState: 'auth.json' });
test('Access protected page', async ({ page }) => {
await page.goto('https://your-app.com/dashboard');
await expect(page).toHaveURL('**/dashboard');
});
3. Method 2: Inject JWT Directly into LocalStorage (Fast, but Less Realistic)
If you already have a valid JWT (e.g., generated via API or hardcoded for test), you can inject it directly into the browser.
๐ง Example (JavaScript/TypeScript)
ts
Copy
Edit
test('Login by injecting JWT', async ({ page }) => {
const jwt = 'your.jwt.token';
await page.addInitScript(([token]) => {
localStorage.setItem('auth_token', token);
}, jwt);
await page.goto('https://your-app.com/dashboard');
await expect(page).toHaveText('Welcome');
});
Adjust the localStorage.setItem('auth_token', ...) key to match your app's actual storage key.
4. Python Example (Using Playwright-Python)
✅ Inject JWT into localStorage
python
Copy
Edit
import asyncio
from playwright.async_api import async_playwright
JWT_TOKEN = "your.jwt.token"
async def run():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
context = await browser.new_context()
page = await context.new_page()
await page.add_init_script(f"""
window.localStorage.setItem('auth_token', '{JWT_TOKEN}');
""")
await page.goto("https://your-app.com/dashboard")
await asyncio.sleep(3)
await browser.close()
asyncio.run(run())
✅ Tips for JWT Testing
Use a mock or test environment that accepts a test JWT or exposes a login API.
If JWT is stored in cookies, you can set them manually using:
ts
Copy
Edit
context.addCookies([{ name: 'token', value: 'abc', domain: 'your-app.com' }])
Avoid hardcoding JWTs that expire quickly — consider using test tokens with long TTLs or regenerating them via API.
Use Playwright's storage state to avoid repeating login flows.
✅ Conclusion
Playwright offers flexible ways to test JWT-based authentication:
Use the UI flow + storage state for full E2E coverage.
Use JWT injection into localStorage for fast, repeatable access to protected routes.
Choose the approach based on your test coverage goals, speed, and realism.
Learn Playwright Training Course in Hyderabad
Read More
Component Testing with Playwright
Accessibility Testing with Playwright
Multi-Tab Testing in Playwright
Testing Shadow DOM Elements with Playwright
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment