Skip to content

Instantly share code, notes, and snippets.

@Blackmorse
Last active February 24, 2022 07:56
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 Blackmorse/cdb5e13d749e7902ad47d5a168dd23ca to your computer and use it in GitHub Desktop.
Save Blackmorse/cdb5e13d749e7902ad47d5a168dd23ca to your computer and use it in GitHub Desktop.
Akka http OAUTH GET requests
import java.net.URLEncoder
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.model.headers.RawHeader
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64
import scala.util.Random
case class OauthTokens(oauthToken: String,
oauthCustomerKey: String,
clientSecret: String,
tokenSecret: String)
val URL = "..."
val API_ENDPOINT = "/..."
def create(requestParams: Map[String, String])
(implicit oauthTokens: OauthTokens): HttpRequest = {
val url = API_ENDPOINT + "?" +
requestParams.map{case(key, value) => s"$key=$value"}.mkString("&")
val oauthNonce = System.currentTimeMillis() / 1000 + new Random().nextInt()
val oauthTimestamp = System.currentTimeMillis() / 1000
val oauthSignatureMethod = "HMAC-SHA1"
val oauthVersion = "1.0"
val oauthParameters = Map[String, String](
"oauth_nonce" -> oauthNonce.toString,
"oauth_timestamp" -> oauthTimestamp.toString,
"oauth_consumer_key" -> oauthTokens.oauthCustomerKey,
"oauth_token" -> oauthTokens.oauthToken,
"oauth_signature_method" -> oauthSignatureMethod,
"oauth_version" -> oauthVersion
)
val allParams = (oauthParameters ++ requestParams).toSeq.sortBy(_._1)
val urlEncoded = URLEncoder.encode(s"https://$URL" + API_ENDPOINT, "UTF-8")
val paramsStringEncoded = URLEncoder.encode(allParams.map{case (key, value) => s"$key=$value"}.mkString("&"), "UTF-8")
val key = s"${URLEncoder.encode(oauthTokens.clientSecret, "UTF-8")}&${URLEncoder.encode(oauthTokens.tokenSecret, "UTF-8")}"
val toSignString = s"GET&$urlEncoded&$paramsStringEncoded"
val keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1")
val mac = Mac.getInstance("HmacSHA1")
mac.init(keySpec)
val bytes = mac.doFinal(toSignString.getBytes("UTF-8"))
val result = new String(Base64.encodeBase64(bytes)).replace("\r\n", "")
val header = "OAuth " +
(oauthParameters + ("oauth_signature" -> URLEncoder.encode(result, "UTF-8"))).map{case(key, value) => s"""$key="$value""""}.mkString(", ");
HttpRequest(uri = url)
.withHeaders(RawHeader("Authorization", header))
}
@pranavkapoorr
Copy link

Bro do you have any Java version for the same?

@Blackmorse
Copy link
Author

@pranavkapoorr , Unfortunately, no

I guess there should be easy to port it for Java. If you need help with this - feel free to ask

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