【发布时间】:2021-07-10 00:16:06
【问题描述】:
我试图让 puppeteer 发送 Authorization 标头,但没有收到挑战,仅适用于 1 方/2 方请求 - 即不发送给第 3 方,并且不会产生意外后果。主要目标是在需要的地方进行身份验证,并避免泄露Authorization + Referer 的杀手级组合
使用page.authenticate() 是行不通的,因为它需要挑战。使用page.setExtraHTTPHeaders() 设置标头,然后将其发送给第三方。使用page.setRequestInterception() 允许我引入一些条件逻辑,并且确实解决了主要目标,但它似乎增加了一堆复杂性和意想不到的后果(例如围绕缓存)。
我的具体用例是网络字体,fwiw。
以下是我如何确认额外的标头已通过page.setExtraHTTPHeaders(在本例中为 httpbin)发送给第 3 方
向 httpbin.org/headers 提供一个带有 iframe 的简单页面:
var http = require('http')
http.createServer(function (request, response) {
console.log(request.headers)
response.writeHead(200)
response.end('<iframe src="http://httpbin.org/headers" width="100%" height="100%"></iframe>\n')
}).listen(8000)
使用 puppeteer 获取该页面:
const puppeteer = require('puppeteer');
const url = 'http://localhost:8000';
(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.setExtraHTTPHeaders({ Authorization: 'Basic dXNlcjpwYXNz' })
//await page.authenticate({ username: 'user', password: 'pass' })
await page.goto(url)
await page.screenshot({path: '/tmp/headers.png'})
await browser.close()
})()
httpbin.org/headers 响应的内容(通过tcpflow -c 在线捕获):
{
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-GB",
"Authorization": "Basic dXNlcjpwYXNz", <----- Authorization is forwarded
"Host": "httpbin.org",
"Referer": "http://localhost:8000/",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.0 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-5ecdb903-0c61b77370a47d894aa8aa7c"
}
}
【问题讨论】:
标签: node.js puppeteer basic-authentication google-chrome-headless