Scala+Play2.6的OAuth2.0认证--Facebook

本文采用授权码模式,参考https://www.cnblogs.com/y-yxh/p/5903771.html
总结起来就三点:
1.请求fb的认证url,fb会根据浏览器是否已登录而判断是否重定向到登陆页面,然后以url参数形式返回code到你提交的回调地址。
如何请求?下面是一个例子。

 "https://www.facebook.com/dialog/oauth?" +
 "client_id=595xxxxxxx711&" +
 "redirect_uri=http://localhost:9000/fb/auth&" +  //这是在fb app上定义的回调地址,要与后台方法一致
 "scope=public_profile,user_birthday,email&state=xxxx" //如果需要的话,可以在state上加上参数(比如加上页面id等判断该请求从何页面而来)

2.拿着返回来的code,再次请求fb的tokenurl用以交换token,最后同样返回access_token到上文的回调url

"https://graph.facebook.com/oauth/access_token?"+
"client_id=xxx"+
"client_secret=xxx"+
"redirect_uri=xxx"+
"code=xxx"
//这一步需要四个参数,前两个在fb app上,redirect_uri同上,code是上步拿到的

3.(非必须) 用第2步拿到的access_token请求用户信息,姓名email等等。不过既然都第三方认证了,目的基本都是为了用户信息。

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



下面上代码:

  def fbAuth() = Action { request =>
    //不需要的话就不用附带state参数请求
    val stateStr = request.getQueryString("state").getOrElse(throw new MsgException(""))
    //回调地址,即本方法的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标签里。考虑到会暴露client_id以及移植的方便性,未作此处理。当然fb文档里也有纯前端js方法实现的认证,由于安全性原因也未采用。

你可能感兴趣的:(Scala+Play2.6的OAuth2.0认证--Facebook)