You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Puppeteer无头模式传递Bearer Token受阻,求可行解决方案

Puppeteer + Angular: Passing Bearer Token to Headless Browser

Hey Marina, totally get where you're coming from—getting auth working with Puppeteer and Angular can feel like fighting a black box at first, especially when standard solutions don't click. Let's walk through actionable approaches, including the localStorage method you asked about, and other reliable workarounds.

Option 1: Use LocalStorage to Inject the Token/User Object

This is absolutely viable, and it’s probably the closest match to how your Angular app handles auth normally. Here’s how to pull it off:

  1. Identify your app’s storage keys: First, check what key your Angular app uses to store the Bearer Token (and user object, if needed) in localStorage. You can find this by opening your app in a regular browser, navigating to DevTools > Application > LocalStorage. Common keys are things like auth-token, access_token, or currentUser.

  2. Inject the token via Puppeteer: After launching your browser and creating a page, use page.evaluate() to write directly to localStorage before loading your app (or refresh after injecting):

const yourBearerToken = "your-valid-token-here";
const userObject = { id: 123, email: "marina@example.com", /* other user props */ };

await page.evaluate((token, user) => {
  localStorage.setItem("auth-token", token);
  localStorage.setItem("current-user", JSON.stringify(user));
}, yourBearerToken, userObject);

// Reload the page so Angular's auth initializer picks up the new storage values
await page.reload();

Pro tip: If your app uses sessionStorage instead of localStorage, just swap out the method to sessionStorage.setItem().

Option 2: Set Auth Cookies Directly

If your Angular app relies on cookies for auth (either via backend sessions or stored tokens), skip localStorage and set the cookie directly with Puppeteer:

await page.setCookie({
  name: "auth-cookie", // Match your app's cookie name
  value: yourBearerToken,
  domain: "your-app-domain.com", // Must match your Angular app's domain
  path: "/",
  httpOnly: false, // Set to true if the cookie is only accessed by the backend
  secure: true, // Use true in production for HTTPS sites
});

// Refresh to let Angular pick up the cookie
await page.reload();

Option 3: Inject the Token Into All HTTP Requests

If you don’t want to mess with storage or cookies, use Puppeteer’s setExtraHTTPHeaders to automatically add the Authorization header to every request your headless browser makes:

await page.setExtraHTTPHeaders({
  "Authorization": `Bearer ${yourBearerToken}`
});

// Now navigate to your app—all requests will include the token
await page.goto("https://your-app.com");

Note: This applies to all requests (including static assets like CSS/JS). If your backend blocks requests with Authorization headers for static resources, use a request interceptor to target only API calls instead:

await page.setRequestInterception(true);
page.on("request", (req) => {
  if (req.url().includes("/api/")) { // Target only API endpoints
    req.continue({
      headers: { ...req.headers(), Authorization: `Bearer ${yourBearerToken}` }
    });
  } else {
    req.continue();
  }
});

Option 4: Simulate the Full Login Flow (Fallback)

If all else fails, simulate a real user login—this is the most reliable method because it mimics exactly how a human would authenticate. Here’s a quick example:

await page.goto("https://your-app.com/login");

// Wait for the login form to load
await page.waitForSelector("#email-input");

// Enter credentials and submit
await page.type("#email-input", "marina@example.com");
await page.type("#password-input", "your-password");
await page.click("#submit-login");

// Wait for navigation to the authenticated page
await page.waitForNavigation({ waitUntil: "networkidle2" });

Key Troubleshooting Tips

  • Headless detection: Some Angular apps block headless browsers. Add these args when launching Puppeteer to avoid this:
    const browser = await puppeteer.launch({
      headless: "new",
      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
      ]
    });
    
  • Token validity: Double-check that your Bearer Token isn’t expired—expired tokens will fail silently even if injected correctly.
  • Angular auth initialization: Make sure your app’s auth service reads from storage/cookies on page load (most do, but if yours only checks on app boot, a reload is necessary after injection).

内容的提问来源于stack exchange,提问作者Marina M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:16:40