Skip to content

Instantly share code, notes, and snippets.

@ericktai
Created August 21, 2012 00:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericktai/9515a7ecdbb5625b348b to your computer and use it in GitHub Desktop.
Save ericktai/9515a7ecdbb5625b348b to your computer and use it in GitHub Desktop.
JS to generate OAuth 2.0 Authorization Header
function createBaseString(ts, nonce, method, uri, host, port) {
var nl = '\u000A';
return ts + nl + nonce + nl + method + nl + uri + nl + host + nl + port + nl + nl;
}
function generateMAC(method, id, key, hostWithPort, url) {
var splitHost = hostWithPort.split(':');
var hostNoPort = splitHost.length > 1 ? splitHost[0] : hostWithPort;
var port = splitHost.length > 1 ? splitHost[1] : 80;
var ts = Math.round(new Date().getTime() / 1000);
var nonce = "n" + Math.round(Math.random() * 10000);
var base = createBaseString(ts, nonce, method, url, hostNoPort, port);
var hash = CryptoJS.HmacSHA1(base, key);
var mac = hash.toString(CryptoJS.enc.Base64);
return 'MAC id="' + id + '",ts="' + ts + '",nonce="' + nonce + '",mac="' + mac + '"';
}
function getAuthHeader(method, params){
var host = StackMob.getBaseURL();
var path = params['url'].replace(new RegExp(host, 'g'), '/');
var sighost = host.replace(new RegExp('^http://|^https://', 'g'), '').replace(new RegExp('/'), '');
var accessToken = StackMob.Storage.retrieve('oauth2.accessToken');
var macKey = StackMob.Storage.retrieve('oauth2.macKey');
var expires = StackMob.Storage.retrieve('oauth2.expires');
if(StackMob.isOAuth2Mode() && accessToken && macKey) {
var authHeader = generateMAC(StackMob.METHOD_MAP[method] || 'GET', accessToken, macKey, sighost, path);
return authHeader;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment