-
-
Save ericktai/9515a7ecdbb5625b348b to your computer and use it in GitHub Desktop.
JS to generate OAuth 2.0 Authorization Header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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