下面显示了使用Oauth和Twitter的游戏示例。
在Play框架中,我仍在学习如何使用重定向和路由。 您将如何设置路由文件和 Appliction.scala 文件来处理此重定向?
Redirect(routes.Application.index).withSession("token" -> t.token, "secret" -> t.secret)
路线会是这样的吗?
GET /index controllers.Application.index(String, String)
链接到包含示例代码 http://www.playframework.com/documentation/2.0/ScalaOAuth 的 Play 框架文档
object Twitter extends Controller {
val KEY = ConsumerKey("xxxxx", "xxxxx")
val TWITTER = OAuth(ServiceInfo(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"https://api.twitter.com/oauth/authorize", KEY),
false)
def authenticate = Action { request =>
request.queryString.get("oauth_verifier").flatMap(_.headOption).map { verifier =>
val tokenPair = sessionTokenPair(request).get
// We got the verifier; now get the access token, store it and back to index
TWITTER.retrieveAccessToken(tokenPair, verifier) match {
case Right(t) => {
// We received the authorized tokens in the OAuth object - store it before we proceed
Redirect(routes.Application.index).withSession("token" -> t.token, "secret" -> t.secret)
}
case Left(e) => throw e
}
}.getOrElse(
TWITTER.retrieveRequestToken("http://localhost:9000/auth") match {
case Right(t) => {
// We received the unauthorized tokens in the OAuth object - store it before we proceed
Redirect(TWITTER.redirectUrl(t.token)).withSession("token" -> t.token, "secret" -> t.secret)
}
case Left(e) => throw e
})
}
def sessionTokenPair(implicit request: RequestHeader): Option[RequestToken] = {
for {
token <- request.session.get("token")
secret <- request.session.get("secret")
} yield {
RequestToken(token, secret)
}
}
}
事实证明,我在路由和重定向方面遇到如此多间歇性问题的原因是游戏版本,scala版本和Eclipse的ScalaIDE版本的组合。 使用 Play 版本 2.2.3、scala 版本 2.10.4 和 ScalaIDE 版本 2.10.x 解决了路由和重定向问题。
Twitter 示例需要以下导入语句。
import play.api.libs.oauth.ConsumerKey
import play.api.libs.oauth.ServiceInfo
import play.api.libs.oauth.OAuth
import play.api.libs.oauth.RequestToken
如果你的路线是这样的:
GET /index controllers.Application.index(param1:String, param2:String)
然后反向路由将如下所示:
routes.Application.index("p1", "p2")
这将导致这样的事情:
/index?param1=p1¶m2=p2
确保您正在查看的文档版本正确,2.2.x
您需要以下 URL:http://www.playframework.com/documentation/2.2.x/ScalaOAuth