Playwright调用Jira Xray RestAPI获sessionId遇认证403/401求助
Fixing Playwright Basic Authentication for Jira Xray REST API
Your issue stems from Playwright's httpCredentials being designed for browser-level authentication prompts, not direct API requests. Unlike Cypress's auth option which explicitly adds Basic Auth headers, Playwright doesn’t automatically inject these headers into context.request calls. Here are concrete fixes:
Solution 1: Manually Add Basic Auth Header to API Request
Construct the Authorization header directly to ensure credentials are sent with the API call:
const username = 'username'; const password = 'pwd123'; // Encode credentials to Base64 for Basic Auth const authHeader = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`; const context = await browser.newContext(); const sessionResponse = await context.request.get('https://jiraserver.example.com/rest/auth/1/session', { headers: { 'Authorization': authHeader, 'Accept': 'application/json' } }); // Validate request success and extract sessionId expect(sessionResponse.ok()).toBeTruthy(); const sessionData = await sessionResponse.json(); const sessionId = sessionData.session.value;
Solution 2: Use POST Request for Proper Session Creation
Jira’s /rest/auth/1/session endpoint requires a POST request to create a new session (GET only retrieves existing sessions). Use this flow for correct session ID retrieval:
const context = await browser.newContext(); const sessionResponse = await context.request.post('https://jiraserver.example.com/rest/auth/1/session', { headers: { 'Content-Type': 'application/json' }, data: { username: 'username', password: 'pwd123' } }); expect(sessionResponse.ok()).toBeTruthy(); const sessionData = await sessionResponse.json(); const sessionId = sessionData.session.value;
Key Notes
- Your original
httpCredentialssetup won’t work for API requests because it targets browser authentication popups, not HTTP headers. - The Cypress example works because its
authoption explicitly injects the Basic Auth header into the request, which we replicate manually in Solution 1.
内容的提问来源于stack exchange,提问作者Itsmeg3
相关产品推荐
相关产品推荐

