Scala play twitter api oauth authentication not working

using play 2.4 to access twitter api with oauth. I created an app on twitter and created a key and token with secrets. on twitter made up the url for my app as it doesn't actually exist. and used the same composed url for the callback url. Launching the application on localhost. Using the curl command generated from twitter to simulate authentication works as expected, so my keys and tokens are valid.

I get this response when I run my code:

Error 401 Unauthorized

This is the main game code:

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) )

}

      

+3


source to share


2 answers


I think the problem is that you are using a fake Twitter API. As mentioned here , you have to use Twitter API 1.1 so that your web service url is like this:.url("https://stream.twitter.com/1.1/statuses/sample.json")



0


source


My problem must have been the Twitter app I created on Twitter. deleted and recreated the app and it worked fine. I am using game 2.4. The only difference I can think of is that when building the app on twitter for the first time I presented a compiled url that didn't really exist and it didn't work. Then I uninstalled this app and created a new one, but provided my Twitter account url as the website url and it worked.



0


source







All Articles