我正在尝试签署 OAuth 1 令牌请求,特别是:
https://api.twitter.com/oauth/request_token
GitHub Gist HERE,更易于阅读:
def timestamp: String = (System.currentTimeMillis / 1000).toString;
def nonce: String = System.nanoTime.toString
/**
* Generates the OAuth 1 header for a request.
*/
def oauthHeader(
endPoint: String,
requestMethod: String,
consumerKey: String,
callback: String,
params: List[(String, String)] = List()): String = {
val signature = sign(endPoint, requestMethod, consumerKey);
val oauthParams: List[(String, String)] = params :::
(OAuthParams.oauth_consumer_key -> consumerKey) ::
(OAuthParams.oauth_callback -> URLEncoder.encode(callback, UTF_8)) ::
(OAuthParams.oauth_nonce -> nonce) ::
(OAuthParams.oauth_timestamp -> timestamp) ::
(OAuthParams.oauth_signature -> signature) ::
(OAuthParams.oauth_signature_method -> "HMAC-SHA1") ::
(OAuthParams.oauth_version -> "1.0") :: Nil
val encodedParams = oauthParams.sortBy(_._1) map (header => {
header._1 + "=" + "\"" + header._2 + "\""
})
OAuthParams.oauth + " " + encodedParams.mkString(", ")
}
def sign(endPoint: String,
requestMethod: String,
consumerKey: String,
params: List[(String, String)] = List()): String = {
/**
* The map of OAuth params.
* Added to every request.
*/
val oauthParams: List[(String, String)] = params :::
(OAuthParams.oauth_consumer_key -> consumerKey) ::
(OAuthParams.oauth_nonce -> nonce) ::
(OAuthParams.oauth_timestamp -> timestamp) ::
(OAuthParams.oauth_signature_method -> "HMAC-SHA1") ::
(OAuthParams.oauth_version -> "1.0") ::
Nil
/**
* Percent encoded List of parameters.
*/
val signatureMap = oauthParams.sortBy(_._1).map(header => {
URLEncoder.encode(header._1 + "=" + header._2, UTF_8)
});
/**
* Add the request method.
*/
val encodedHeader = requestMethod ::
URLEncoder.encode(endPoint, UTF_8) ::
URLEncoder.encode(oauthParams.mkString("&"), UTF_8) :: Nil
URLEncoder.encode(hmacSha1(encodedHeader.mkString("&"), signinKey), UTF_8);
}
def hmacSha1(value: String, key: String): String = {
val keyBytes = key.getBytes();
val signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
val mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
val rawHmac = mac.doFinal(value.getBytes());
Base64.encodeBase64String(rawHmac)
}
我不断收到:无法验证 oauth 签名和令牌。
假如:
- 申请已注册
- 在应用设置中启用了“使用 Twitter 登录”
我究竟做错了什么?