Skip to content

Instantly share code, notes, and snippets.

@dzuluaga
Last active August 29, 2015 14:12
Show Gist options
  • Save dzuluaga/9a76869ed1318de7494f to your computer and use it in GitHub Desktop.
Save dzuluaga/9a76869ed1318de7494f to your computer and use it in GitHub Desktop.
JavaScript Regular Expression to Parse OAuth 1.0a Authorization Headers
/**
* This function parses a string in a form of an authorization header and returns a string with two elements, the matching string and the
* value. The string has been escaped with http://www.freeformatter.com/javascript-escape.html#ad-output.
*
* @strHeader {string} string in a form of an authorization header
* @patternToMatch {rexexp} regular expression to match specific pattern
* @return {array} Returns an array with two elements: ["oauth_token="mHcOQ4lksgr1UUCcVzNYxNMSbr9Y"", "mHcOQ4lksgr1UUCcVzNYxNMSbr9Y"]
*/
function parseAuthorizationHeader(strHeader, patternToMatch){
return(strHeader.match(patternToMatch));
}
var authorization_header = "Authorization: OAuth realm=\"\",oauth_version=\"1.0\",oauth_consumer_key=\"Csgk9z6lfHk98Jjaa85UgwsZTVfZqCsf\",oauth_token=\"mHcOQ4lksgr1UUCcVzNYxNMSbr9Y\",oauth_timestamp=\"1419906782\",oauth_nonce=\"wskKBcUGFH2\",oauth_signature_method=\"HMAC-SHA1\",oauth_signature=\"qpYYVp0BDJXwdZkiY9AddO%2Fgg9k%3D\""
var regexp = /oauth_token=\"(.+?)\"/i
var oauth_token = parseAuthorizationHeader(authorization_header, regexp);
console.log("oauth_token: " + oauth_token[1]); // return mHcOQ4lksgr1UUCcVzNYxNMSbr9Y
console.log(oauth_token[1] == 'mHcOQ4lksgr1UUCcVzNYxNMSbr9Y'); // Expected to be true
@dzuluaga
Copy link
Author

Comment!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment