Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - PhantomJS doesn't send authentication header

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();
  });
}

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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';

you can use:

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

(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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...