2013-10-15 61 views
0

我是新來播放的框架,所以我是新來確保社會。我必須在一個項目中實現Google身份驗證,但我不知道我應該如何連接到Gmail。我所擁有的是一個擴展的身份像這樣的賬戶類:確保社會連接提供商

case class Account(
       identityId: IdentityId, 
       firstName: String, 
       lastName: String, 
       fullName: String, 
       email: Option[String], 
       avatarUrl: Option[String], 
       authMethod: AuthenticationMethod, 
       oAuth1Info: Option[OAuth1Info] = None, 
       oAuth2Info: Option[OAuth2Info] = None, 
       passwordInfo: Option[PasswordInfo] = None 
       )extends Identity 

然後,我創建帳戶的集合,迭代它們並識別用戶想要連接的提供者。

for(account <- accounts){ 
     if(account.identityId.providerId == service){ 
     //Sends account info to securesocial module 
      success = true 
     } 
    } 

我該如何稱呼安全社交API才能連接到服務,在這種情況下,Gmail?

回答

1
  1. 爲用戶提供一個選擇界面。
  2. 註冊與Google API Console您的應用程序。創建2個ID用於測試,另一個用於產品。
  3. 一個重定向到谷歌服務器上創建一個按鈕。

的URL看起來是這樣的:

https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&client_id=your_client_id&redirect_uri=your_redirect_uri

  1. 被重新定向到上面的鏈接後,用戶可以嚮應用的訪問權限谷歌帳戶。
  2. 而谷歌重定向用戶到您的網站,但它包括一個code令牌。

您需要3種主要的方法:

case class GoogleTokenResponse(
     access_token: String, 
     token_type: String, 
     expires_in: String, 
     id_token: String 
    ); 
    def getAccessToken: GoogleTokenResponse 
    // this is an HTTP request to https://accounts.google.com:443?code=the_code_param 

    def getUserData: HttpResponse 
    // this will get the user data from www.googleapis.com 
    // it needs the OAuth2 access_token obtained above. 
    val req = url("https://www.googleapis.com")/"oauth2"/"v2"/"userinfo" <<? ("alt" -> "json") <<? 
    Map(OAuthParams.access_token -> token.access_token); // this is a databinder dispatch call. 

    // this is how a Google profile response looks like. 
    case class GoogleUserResponse(
     val id: String, 
     val name: String, 
     val given_name: String, 
     val family_name: String, 
     val verified_email: Boolean, 
     val email: String, 
     val locale: Option[String], 
     val link: Option[String], 
     val hd: Option[String] 
    ) 

現在你有一個反應,它映射到自己的自定義用戶執行。

最後階段是:

  • 如果用戶已經存在(存儲GoogleID用戶通過它可以搜索,不要用郵件用於此目的)

  • 如果用戶沒有按不存在,添加它們,請求更多詳細信息等。

  • 在這兩種情況下,都通過爲用戶創建會話來驗證用戶身份。
1

您不必自己連接到Google。 SecureSocial爲您處理所有的身份驗證流程。你需要的是:

1)添加一個鏈接到谷歌,使用戶點擊那裏,並啓動身份驗證流程 2)實施UserService,以便SecureSocial可以將用戶保存在您的數據庫中。 3)註冊在play.plugins文件中的谷歌插件。 4)使用SecuredAction,而不是建立在操作播放的保護你的行動。

SecuredAction攔截請求,並在用戶未通過身份驗證時將用戶重定向到登錄頁面。

查看模塊附帶的示例應用程序,它們提供了一個基本框架,您可以使用該框架擴展以構建應用程序。