Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Play 2.0 自己實作新浪微博 OAuth2.0 登入

手上專案需要接微博聯合登入。官方 Java 版 SDK 對不熟 Java 的人來說門檻偏高,而 OAuth2 的授權流程其實並不複雜,於是就自己動手實作了一遍,順便練手。以下以 Play 2.0 與 Scala 為例。

OAuth2 庫程式碼

package libs.oauth2

import play.api.libs.concurrent._
import play.api.libs.ws._
import play.core.parsers._
import play.api.libs.json._

case class OAuthKey(key: String, secret: String)
case class AccessToken(token: String)
case class AccessTokenError(error: String, errorCode: Int, request: String)

case class OAuth2(authorizationUrl: String,
                  accessToken: String,
                  redirectUri: String,
                  key: OAuthKey) {

  def authorization(responseType: String, params: Map[String, String]) = {
    val ism = if (authorizationUrl.indexOf("?") > 0) "&" else "?"
    authorizationUrl + ism + "client_id=" + key.key +
      "&response_type=" + responseType +
      "&redirect_uri=" + java.net.URLEncoder.encode(redirectUri, "utf-8")
  }

  def getAccessToken(code: String): Either[AccessToken, AccessTokenError] = {
    val rs = WS.url(accessToken).withQueryString(
        ("client_id", key.key),
        ("client_secret", key.secret),
        ("grant_type", "authorization_code"),
        ("redirect_uri", redirectUri),
        ("code", code)).post("content").value.get.body

    var jsonRs = Json.parse(rs)
    if (rs.indexOf("error") > 0) {
      Right(AccessTokenError((jsonRs \ "error").as[String],
                             (jsonRs \ "error_code").as[Int],
                             (jsonRs \ "request").as[String]))
    } else {
      Left(AccessToken((jsonRs \ "access_token").as[String]))
    }
  }
}

使用範例

object login extends Controller {
  val oauth2 = OAuth2(
      "https://api.weibo.com/oauth2/authorize",
      "https://api.weibo.com/oauth2/access_token",
      "https://xx.com/login/sinare",
      OAuthKey("key", "secret")
  )

  def sina = Action {
    Redirect(oauth2.authorization("code", Map()))
  }

  def sinare = Action { implicit request =>
    request.queryString.getOrElse("code", "".toSeq).mkString match {
      case code: String if !code.isEmpty => {
        oauth2.getAccessToken(code) match {
          case Left(t)        => Ok("token:" + t.token)
          case Right(error)   => Ok("error" + error.error)
        }
      }
      case _ => Ok("error")
    }
  }
}

流程與設計說明

整個流程就是標準的授權碼模式:使用者造訪 /login/sina 時被導向微博授權頁,授權後微博會帶著 code 回跳到 redirectUri;回調端點取出 code,向 access_token 端點換取權杖。

這裡有兩個設計值得留意。第一,用 Either 表達「成功或失敗」比拋例外更貼近 Scala 的習慣,呼叫端只要用 match 分流即可。第二,判斷是否出錯目前是用 rs.indexOf("error") > 0 這種字串搜尋,實務上建議改成解析 JSON 後檢查欄位是否存在,避免權杖內容剛好含 "error" 時誤判。另外正式環境請把 client_secret 放到設定檔或環境變數,不要寫死在程式碼裡。

Copyright © Linux教程網 All Rights Reserved