Skip to content

Instantly share code, notes, and snippets.

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 iskandarsaleh/79a12d680e701808b5b3240ebe17c8cd to your computer and use it in GitHub Desktop.
Save iskandarsaleh/79a12d680e701808b5b3240ebe17c8cd to your computer and use it in GitHub Desktop.
Generating an OAuth1 Authorization header with HMAC-SHA1 in Groovy
import org.apache.commons.lang.RandomStringUtils
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
class OAuth1AuthorizationUtil {
public static String generateOAuthAuthorizationHeader(String method, String url, String consumerKey, String consumerSecret) {
generateOAuthAuthorizationHeader(method, url, consumerKey, consumerSecret, [:])
}
public static String generateOAuthAuthorizationHeader(String method, String url, String consumerKey, String consumerSecret, Map additionalParameters) {
def signatureMethod = 'HMAC-SHA1'
def version = '1.0'
// Get timestamp in seconds
def timestamp = "${Math.round(new Date().getTime()/1000)}";
// OAuth nonce consists of 6 randomly generated characters, which must be unique for each request.
def nonce = RandomStringUtils.random(6, true, true)
def oAuthParameters = [
oauth_consumer_key: consumerKey,
oauth_nonce: nonce,
oauth_signature_method: signatureMethod,
oauth_timestamp: timestamp,
oauth_version: version
]
// Combine oAuth parameters and additional request parameters to generate signature
def signature = generateOAuthSignature(method, url, consumerSecret, oAuthParameters + additionalParameters)
"OAuth oauth_consumer_key=\"${consumerKey}\"," +
"oauth_signature_method=\"${signatureMethod}\"," +
"oauth_timestamp=\"${timestamp}\"," +
"oauth_nonce=\"${nonce}\"," +
"oauth_version=\"${version}\"," +
"oauth_signature=\"${encode(signature)}\""
}
private static String generateOAuthSignature(String method, String url, String consumerSecret, Map parameters) {
// Sort parameters and join with ampersand
signatureParameters = parameters.sort { it.key }.collect { it.key + '=' + it.value }.join('&')
def baseString = "${method}&${encode(url)}&${encode(signatureParameters)}"
// Generate HMAC-SHA1
def keySpec = new SecretKeySpec((consumerSecret + '&').bytes, 'HmacSHA1')
def mac = Mac.getInstance('HmacSHA1');
mac.init(keySpec)
def calculatedBytes = mac.doFinal(baseString.getBytes('UTF-8'))
// Base64 encode the HMAC
new String(Base64.encoder.encode(calculatedBytes))
}
private static String encode(String stringToEncode) {
URLEncoder.encode(stringToEncode, 'UTF-8')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment