Scala+Play2.6的OAuth2.0認(rèn)證--Facebook

本文采用授權(quán)碼模式,參考https://www.cnblogs.com/y-yxh/p/5903771.html
總結(jié)起來就三點:
1.請求fb的認(rèn)證url,fb會根據(jù)瀏覽器是否已登錄而判斷是否重定向到登陸頁面,然后以url參數(shù)形式返回code到你提交的回調(diào)地址。
如何請求?下面是一個例子。

 "https://www.facebook.com/dialog/oauth?" +
 "client_id=595xxxxxxx711&" +
 "redirect_uri=http://localhost:9000/fb/auth&" +  //這是在fb app上定義的回調(diào)地址,要與后臺方法一致
 "scope=public_profile,user_birthday,email&state=xxxx" //如果需要的話,可以在state上加上參數(shù)(比如加上頁面id等判斷該請求從何頁面而來)

2.拿著返回來的code,再次請求fb的tokenurl用以交換token,最后同樣返回access_token到上文的回調(diào)url

"https://graph.facebook.com/oauth/access_token?"+
"client_id=xxx"+
"client_secret=xxx"+
"redirect_uri=xxx"+
"code=xxx"
//這一步需要四個參數(shù),前兩個在fb app上,redirect_uri同上,code是上步拿到的

3.(非必須) 用第2步拿到的access_token請求用戶信息,姓名email等等。不過既然都第三方認(rèn)證了,目的基本都是為了用戶信息。

"https://graph.facebook.com/me"



下面上代碼:

  def fbAuth() = Action { request =>
    //不需要的話就不用附帶state參數(shù)請求
    val stateStr = request.getQueryString("state").getOrElse(throw new MsgException(""))
    //回調(diào)地址,即本方法的url
    val selfUri = "http://" + request.host + request.path
 
    request.getQueryString("code") match {
      case Some(code) =>
        //第二次請求
        val f = ws.url(fb.tokenUrl).addQueryStringParameters( //ws是play.api.libs.ws.WSClient
          "client_id" -> fb.clientId,
          "redirect_uri" -> selfUri,
          "client_secret" -> fb.clientSecret,
          "code" -> code
        ).get().flatMap { response =>
            if (response.status == 200) {
              (response.json \ "access_token").asOpt[String] match {
                case Some(token) =>
                  ws.url(fb.getInfoUrl).addQueryStringParameters( //第三步請求用戶信息
                    "fields" -> fb.getInfoFields,
                    "access_token" -> token
                  ).get().map { userInfo =>
                      if (userInfo.status == 200) {
                        Ok(userInfo.json)
                      } else {
                        BadRequest(userInfo.json)
                      }
                    }
                case _ => Future(Unauthorized)
              }
            } else {
              Future(BadRequest)
            }
          }
        val result = Await.result(f, Duration.Inf)
        result
      case _ => //第一次請求
Redirect(
        s"${fb.requestUrl}?client_id=${fb.clientId}&redirect_uri=$selfUri&scope=${fb.requestScope}&state=$stateStr"
      )
    }
  }

fb.tokenUrl等等部分我寫在了application.conf里,如下

fb {
    clientId="5xxxxx1"
    clientSecret="7xxxxxxx2"
    requestUrl="https://www.facebook.com/dialog/oauth"
    requestScope="public_profile,user_birthday,email"
    tokenUrl="https://graph.facebook.com/oauth/access_token"
    #https://graph.facebook.com/me?fields=id,picture,name,birthday,email&access_token=xxx
    getInfoUrl="https://graph.facebook.com/me"
    getInfoFields="id,picture,name,birthday,email"
  }

最后在頁面上會打印出請求到的用戶信息。



另外也可以把第一步的請求url寫道html的a標(biāo)簽里。考慮到會暴露client_id以及移植的方便性,未作此處理。當(dāng)然fb文檔里也有純前端js方法實現(xiàn)的認(rèn)證,由于安全性原因也未采用。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容