How to use UrlFetchApp with credentials? Google Scripts

user3586062 picture user3586062 · May 8, 2014 · Viewed 32.4k times · Source

I am trying to use Google Scripts UrlFetchApp to access a website with a basic username and password. As soon as I connect to the site a popup appears that requires authentication. I know the Login and Password, however I do not know how to pass them within the UrlFetchApp.

var response = UrlFetchApp.fetch("htp://00.000.000.000:0000/‎");   
Logger.log(response.getContentText("UTF-8"));

Currently running that code returns "Access Denied". The above code does not contain the actual address I am connecting to for security reasons. A "t" is missing from all the "http" in the code examples because they are being detected as links and Stackoverflow does not allow me to submit more than two links.

How can I pass the Login and Password along with my request? Also is there anyway I can continue my session once I have logged in? Or will my next UrlFetchApp request be sent from another Google server requiring me to login again?

The goal here is to login to the website behind Googles network infrastructure so it can act as a proxy then I need to issue another UrlFetchApp request to the same address that would look something like this:

var response = UrlFetchApp.fetch("htp://00.000.000.000:0000/vuze/rpc?json={"method":"torrent-add","arguments":{"filename":"htp://vodo.net/media/torrents/anything.torrent","download-dir":"C:\\temp"}}‎");   
Logger.log(response.getContentText("UTF-8"));

Answer

user3586062 picture user3586062 · May 18, 2014

This question has been answered on another else where. Here is the summary:

Bruce Mcpherson

basic authentication looks like this...
    var options = {};
    options.headers = {"Authorization": "Basic " + Utilities.base64Encode(username + ":" + password)};

Lenny Cunningham

//Added Basic Authorization//////////////////////////////////////////////////////////////////////////////////////////

  var USERNAME = PropertiesService.getScriptProperties().getProperty('username');
  var PASSWORD = PropertiesService.getScriptProperties().getProperty('password');

  var url = PropertiesService.getScriptProperties().getProperty('url');//////////////////////////Forwarded

Ports to WebRelay

  var headers = {
    "Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
  };

  var params = {
    "method":"GET",
    "headers":headers
  };

var reponse = UrlFetchApp.fetch(url, params);