2015-06-17 87 views
3

使用play 2.4通過oauth訪問twitter api。 我在twitter上創建了一個應用程序,並創建了帶有祕密的密鑰和標記。由於它實際上並不存在,所以twitter上的 組成了我的應用程序的URL。 和在回調url中使用了相同的url。在localhost上運行應用程序。使用curl生成的twitter命令來模擬身份驗證的工作,因爲我的密鑰和令牌是有效的。scala play twitter api oauth身份驗證不起作用

我得到這個響應,當我運行我的代碼:

錯誤401未經授權

這是主戲碼:

import play.api._ 
import play.api.mvc._ 
import play.api.libs.concurrent.Execution.Implicits._ 
import play.api.Play.current 
import play.api.libs.oauth.{ConsumerKey,RequestToken} 
import scala.concurrent.Future 
import play.api.libs.ws._ 
import play.api.libs.oauth.OAuthCalculator 
import play.api.libs.iteratee._ 

class Application extends Controller { 

    def index = Action { 
    Ok(views.html.index("Your new application is ready.")) 
    } 

    val loggingIteratee = Iteratee.foreach[Array[Byte]] { array => Logger.info(array.map(_.toChar).mkString) } 

    def tweets = Action.async { 
    credentials.map { 
     case (consumerKey, requestToken) => 
     println(consumerKey.key.toString()) 
     println(consumerKey.secret.toString()) 
     println(requestToken.token.toString()) 
     println(requestToken.secret.toString()) 
     WS 
      .url("https://stream.twitter.com/1.1/statuses/sample.json") 
      .sign(OAuthCalculator(consumerKey, requestToken)) 
      .withQueryString("track" -> "reactive") 
      .get() 
      .map { response => 
      Ok(response.body) 
      } 
    }getOrElse{ 
     Future{ 
     InternalServerError("twitter credentials missing") 
     } 
    } 
    } 

    def credentials :Option[(ConsumerKey,RequestToken)] = for { 
     apiKey <- Play.configuration.getString("twitter.apiKey") 
     apiSecret <- Play.configuration.getString("twitter.apiSecret") 
     token <- Play.configuration.getString("twitter.token") 
     tokenSecret <- Play.configuration.getString("twitter.tokenSecret") 
    }yield (ConsumerKey(apiKey,apiSecret),RequestToken(token,tokenSecret)) 

} 
+0

播放2.4 oauth已損壞。 – bwawok

+1

@bwawok有沒有一個bug?因爲它是一個已知的問題? –

+0

我這麼認爲,通過https://github.com/playframework/playframework/pull/4826進行故障排除。到目前爲止,看起來像異步http的東西是錯誤的,並獲得了2.4版本的升級。我敢打賭你的代碼在2.3中起作用。 – bwawok

回答

0

我認爲這個問題是您使用虛假的Twitter API 。正如提到here你必須使用Twitter的API 1.1,所以你的網絡服務的URL應該是:.url("https://stream.twitter.com/1.1/statuses/sample.json")

+1

我試過了,我仍然得到相同的答覆.. –

+0

正如你使用cURL是twurl從twitter或正常的捲曲? – alexfi

+0

是的,我使用CURL檢查了我生成的令牌和密鑰,它工作正常。 –

0

我的問題必須與我在Twitter上創建的Twitter應用程序。刪除並重新創建應用程序,它工作正常。我正在使用2.4。我能想到的唯一區別是,當我第一次在twitter上創建應用程序時,我提供了一個製作完成的url,它實際上並不存在,並且它不起作用。然後,我刪除了該應用程序,並創建了一個新的應用程序,但提供了我的Twitter帳戶URL作爲網址,並且它工作正常