我正在我的网站上将登录与 Twitter 集成,我现在完全陷入困境。我正在遵循本指南:(https://dev.twitter.com/docs/auth/implementing-sign-twitter)并且正在使用 Play 框架在 Scala 中进行操作。
我读过很多人一直收到 401 Unauthorized 错误,我之前在“第 1 步:获取请求令牌”中也是如此,但我通过不传递我在这里找到的 oauth_callback_url 解决了这个问题:https:/ /github.com/cyrus7580/twitter_api_examples/blob/master/src/SampleTwitterRequests.java
现在我的问题是“第 3 步:将请求令牌转换为访问令牌”,最后一步......问题是当我对 oauth/access_token 端点进行 POST 时。我得到 401 - Unauthorized - Invalid request token。
我从“步骤 2”中获得了请求令牌和验证者。
第 3 步的代码如下所示:
val token = "R6qe*********************PbTAvlHw" //Got this from step 2
val verifier = "s1jWnOz********************eJEU" //Got this from step 2
val twitterConsumerKey = "iLRU**********uQ"
val twitterConsumerSecret = "DsdGs***********dgfd2"
val signatureMethod = "HMAC-SHA1"
val version = "1.0"
val nonce = getNonce() //method return a 32character random nonce (worked in step 2)
val timeStamp = (System.currentTimeMillis / 1000).toString
val parameterString:String =
"oauth_consumer_key=" + twitterConsumerKey +
"&oauth_nonce=" + nonce +
"&oauth_signature_method=" + signatureMethod +
"&oauth_timestamp=" + timeStamp +
"&oauth_token=" + URLEncoder.encode(token, "UTF-8") +
"&oauth_version=" + version
val baseString:String = "POST&"+ URLEncoder.encode("https://api.twitter.com/oauth/access_token", "UTF-8")+"&"+ URLEncoder.encode(parameterString2, "UTF-8")
val signature = getSignature(twitterConsumerSecret, baseString, "HmacSHA1")
val data = "OAuth " +
"oauth_consumer_key=\"" + twitterConsumerKey +
"\",oauth_signature_method=\"" + signatureMethod +
"\",oauth_timestamp=\"" + timeStamp +
"\",oauth_nonce=\"" + nonce +
"\",oauth_version=\"" + version +
"\",oauth_signature=\"" + signature +
"\",oauth_token=\"" + URLEncoder.encode(token, "UTF-8") + "\""
Async{
WS.url("https://api.twitter.com/oauth/request_token").withHeaders("Authorization" -> data).post("oauth_verifier="+URLEncoder.encode(verifier, "UTF-8")).map(response => {
Logger.info(response.body.toString()) //Invalid request token
Logger.info(response.status.toString) //401
Logger.info(response.statusText) //Unauthorized
Ok("Welcome")
})
}
getSignature(twitterConsumerSecret, baseString, "HmacSHA1") 看起来像这样:
def getSignature(consumerSecret:String, baseString:String, algorithm:String):String = {
val key:String = consumerSecret + "&"
val signingKey:SecretKeySpec = new SecretKeySpec(key.getBytes(), algorithm)
try{
var mac: Mac = null;
mac = Mac.getInstance(algorithm);
mac.init(signingKey);
val rawHmac:Array[Byte] = mac.doFinal(baseString.getBytes());
val oauth_signature:String = new sun.misc.BASE64Encoder().encode(rawHmac)
val oauth_signatureFinal:String = URLEncoder.encode(oauth_signature, "UTF-8")
return oauth_signatureFinal
}
}
我希望有人对此有任何想法。提前致谢!