What is Basic HTTP Authentication

Basic HTTP Authentication is one of the simplest ways for providing username and password in HTTP request. It uses just fields in HTTP header without handshaking.

 

Work to do on a Client side

Make Authorization filed in HTTP header by following below steps.

  1. Make a String concatenating username, a single colon(‘:’) and password
  2. Encode the string in Base64
  3. Set ‘Basic ‘ + encoded string as the value of Authorization ‘key’ in header(Make sure to put a white space next to Basic)

 

I’m using javascript to make a code to be executed as a standalone in Ubuntu or Google App Script to manipulate data on Google Drive. Node.js and GAS provides different API for Base64 encoding and I show the examples of how to implement Basic HTTP Authentication in Node.js and GAS.

Example

Example in Node.js

var options = {
host: ‘https://a.b.com’,
port: 443,
path: ‘/’,
// authentication headers
headers: {
‘Authorization’: ‘Basic ‘ + new Buffer(username + ‘:’ + password).toString(‘base64’)
}
};

Node.js provides Buffer object to support Base64 encoding.

Example in Google Apps Script(GAS)

var url = “https://a.b.com”
var options =
{
“method”: “post”,
“headers”: {
“User-Agent”: “MY_APP_NAME”,
“Authorization”: “Basic ” + Utilities.base64Encode(username + ‘:’ + password)
},
“payload”: payload
};

UrlFetchApp.fetch(url, options);

Whereas GAS has Utilities Script Service and base64Encode is one of functions it supports.

 

I hope this post to be a small tip.

javakys

Advertisements