Skip to content

Instantly share code, notes, and snippets.

@pulkitsinghal
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pulkitsinghal/10946736 to your computer and use it in GitHub Desktop.
Save pulkitsinghal/10946736 to your computer and use it in GitHub Desktop.
Set basic authN (authorization header) for an APIGEE target request
var url = context.getVariable('request.queryparam.url');
var username = context.getVariable('request.queryparam.username');
var password = context.getVariable('request.queryparam.password');
if (url && username && password) {
context.setVariable('target.url',url);
// TODO: setup Basic authN (username/password) somehow
// try#1 - http://apigee.com/docs/api-services/api/variables-reference
/*
context.setVariable(
request.header.{header_name} = 'Basic username:password';
);*/
// try#2 - http://apigee.com/docs/api-services/content/javascript-object-model
/*
request.headers['Authorization'] = 'Basic username:password';
context.proxyRequest.headers['Authorization'] = 'Basic username:password';
*/
// try#3 - use python
// a) http://stackoverflow.com/questions/21164916/adding-basic-auth-to-a-service-callout-policy/21174495#21174495
// b) http://stackoverflow.com/questions/21056816/base64-encoding-in-an-apigee-edge-policy/21057641#21057641
// try#4 - use javascript
// a) http://stackoverflow.com/questions/21056816/base64-encoding-in-an-apigee-edge-policy/22455968#22455968
// a.1) https://github.com/apigee/api-platform-samples/blob/master/sample-proxies/base64encoder/apiproxy/resources/jsc/encodeAuthHeader.js
var words = CryptoJS.enc.Latin1.parse(username + ":" + password);
var base64 = CryptoJS.enc.Base64.stringify(words);
//context.setVariable("encodedAuthHeader","Basic " + base64);
request.headers['Authorization'] = 'Basic ' + base64;
}
<Javascript timeLimit="200" name="my-javascript-policy">
<DisplayName>my-javascript-policy</DisplayName>
<IncludeURL>jsc://core-min.js</IncludeURL>
<IncludeURL>jsc://enc-utf16-min.js</IncludeURL>
<IncludeURL>jsc://enc-base64-min.js</IncludeURL>
<ResourceURL>jsc://my-script.js</ResourceURL>
</Javascript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment