Friday, February 17, 2017

Custom Authorization HTTP Request in AWS NodeJS Lambda function

Below is the sample code for AWS NodeJS lambda function. This will show how to make an HTTP request with Custom Authorization using "request" node module.
request v2.79.0 - Simplified HTTP request client.
Request package is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.

/// Module to test HTTP POST Request
/// Created By: Sohan Fegade
/// Created Date: 17-Feb-2017

var request = require('request');
var buffer = require('buffer');

console.log('Loading http-test-module');

exports.handler = function (event, context, callback) {

    if (event != null) {
        console.log('event = ' + JSON.stringify(event));

        var username = 'sampleuser';
        var password = 'samplepassword';
       
        var auth = 'Basic ' + buffer.Buffer(username + ':' + password).toString('base64');
       
        var options = {
            url: 'https://www.sample-auth-url.com/oauth/token',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': auth
            },
            json: {
                'type': 'test',
                'input': 'test',
                'field': 'test',
                'scope': 'urn:scope-api',
                'token-type': 'auth-token'
            }
        }

        request.post(options, function (error, response, body) {
            if (!error && response.statusCode === 200) {
               console.log('Access Token : ' + body.access-token);
            }
               
            context.callbackWaitsForEmptyEventLoop = false;
            callback(null, 'SUCCESS');
       });
    }
    else {
        console.log('No event object');
    }
};
 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.