PhantomJS不发送身份验证标头 [英] PhantomJS doesn't send authentication header

查看:378
本文介绍了PhantomJS不发送身份验证标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PhantomJS中打开需要HTTP身份验证的网页。
我的脚本基于loadspeed.js示例:

I'm trying to open a web page which requires HTTP authentication, in PhantomJS. My script is based off the loadspeed.js example:

var page = require('webpage').create(),
    t, address;
page.settings.userName = "user";
page.settings.password = "password";
if (phantom.args.length === 0) {
  console.log('Usage: loadspeed.js <some URL>');
  phantom.exit();
} else {
  t = Date.now();
  address = phantom.args[0];
  page.open(address, function (status) {
      if (status !== 'success') {
          console.log('FAIL to load the address');
      } else {
          t = Date.now() - t;
          console.log('Loading time ' + t + ' msec');
          page.render('page.jpg');
      }
      phantom.exit();
  });
}

我可以从渲染的page.jpg看到我得到了401每次。
我还使用Wireshark跟踪HTTP会话,这表明在给定URL的GET请求中没有发送认证头。

I can see from the rendered page.jpg that I'm getting a 401 every time. I've also traced the HTTP session using Wireshark, which reveals that no authentication header is sent in the GET request to the given URL.

我是什么在这做错了?我刚刚开始使用PhantomJS,但我整个晚上一直在寻找并且没有太远...

What am I doing wrong here? I'm just getting started with PhantomJS but I've been searching all evening and not gotten far...

推荐答案

PhantomJS(至少从1.9.0开始)有一个auth的错误:它在没有auth头的情况下发送请求,然后只有在它返回401之后才会再次执行请求,但这次是使用头。 (这是用于GET;使用POST它根本不起作用。)

PhantomJS (at least as of 1.9.0) has a bug with auth: it sends the request without the auth headers, and then only after it gets the 401 back does it do the request again but this time with the headers. (That is for GET; with POST it doesn't work at all.)

解决方法很简单,所以代替:

The workaround is simple, so instead of:

page.settings.userName = 'username';
page.settings.password = 'password';

您可以使用:

page.customHeaders={'Authorization': 'Basic '+btoa('username:password')};

(我刚刚在博文中介绍了这一点:http://darrendev.blogspot.jp/2013/04/phantomjs-post-auth-and-timeouts.html ,并了解了Igor Semenko在PhantomJS邮件列表上的解决方法。)

(I just covered this in a blog post: http://darrendev.blogspot.jp/2013/04/phantomjs-post-auth-and-timeouts.html, and learnt that workaround on the PhantomJS mailing list from Igor Semenko.)

这篇关于PhantomJS不发送身份验证标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆