2012-02-13 29 views
10

我不是程序員,但我需要自己做。我需要一些幫助。使用Google OpenID進行Android身份驗證。接下來是什麼?

我一直在尋找最後兩天的解決方案,我找不到任何。

好的。我正在編寫Android本機應用程序。我的第一個目標是通過Google帳戶(已在手機上設置)實現登錄的可能性。

所以我使用的AccountManager獲得「com.google」賬戶,我正在一個身份驗證令牌是這樣的:

Account[] mAccounts = mAccountManager.getAccountsByType("com.google"); 
AccountManagerFuture<Bundle> response = 
    mAccountManager.getAuthToken(mAccounts[0], "android", null, this, null, null); 

Bundle authTokenBundle; 
String authToken; 

try { 
    authTokenBundle = response.getResult(); 
    authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN).toString(); 
} catch (OperationCanceledException e) { 
    Log.e(TAG, e.getMessage()); 
} catch (AuthenticatorException e) { 
    Log.e(TAG, e.getMessage()); 
} catch (IOException e) { 
    Log.e(TAG, e.getMessage()); 
} 

我的問題是 - 什麼應該是我的下一步是什麼?我如何能夠進一步認證過程?我應該如何使用這個令牌?

我發現了一些資源,但其中大多數都使用OAuth或基於Web。我只需要進行身份驗證(如果可能的話)就可以獲得用戶的姓名(我已經有電子郵件地址),我不需要訪問任何Google服務。

謝謝您提前。

+0

如果你嘗試getAccounts(),不知道它給你的信息?我從來沒有用過它只是讀了一下,但玩了一下 – 2012-05-25 23:36:04

+0

並嘗試這篇文章:http://joakim.erdfelt.com/wiki/index.php/AndroidGetAccount – 2012-05-25 23:51:48

回答

8

實際上,OAuth 2是你想要的,而不是OpenID - OpenID本質上是基於網絡的,所以你需要通過WebView或瀏覽器跳過一些圈。 OAuth 2允許您直接在應用中使用來自AccountManager的帶有Google API的令牌。

在您的來電getAuthToken(),該authTokenType參數是的OAuth 2的範圍,你想成爲userinfo.profileuserinfo.email驗證的電子郵件地址(你已經擁有它,但是你有沒有驗證它,它在理論上可以被欺騙)並獲得用戶的姓名。

這是我在類似情況下使用的全範圍:

private static final String OAUTH2_SCOPE = 
    "oauth2:" + 
    "https://www.googleapis.com/auth/userinfo.profile" + 
    " " + 
    "https://www.googleapis.com/auth/userinfo.email"; 

當然,你可以只使用整個字符串字面內嵌,但我更願意建立起來,並澄清,並將其如果需要的話,可以更容易地進行更改。

在我的情況,我用getAuthTokenByFeatures(),像這樣:

am.getAuthTokenByFeatures("com.google", OAUTH2_SCOPE, null, this, null, null, 
          new AccountManagerCallback<Bundle>() 
{ 
    public void run(AccountManagerFuture<Bundle> future) { 
     try { 
      Bundle bundle = future.getResult(); 
      System.out.println("Got Bundle:\n" + 
           " act name: " + 
           bundle.getString(AccountManager.KEY_ACCOUNT_NAME) + 
           "\n act type: " + 
           bundle.getString(AccountManager.KEY_ACCOUNT_TYPE) + 
           "\n auth token: " + 
           bundle.getString(AccountManager.KEY_AUTHTOKEN)); 
     } catch (Exception e) { 
      System.out.println("getAuthTokenByFeatures() cancelled or failed:"); 
      e.printStackTrace(); 
     } 
    } 
}, null); 

,但你可以使用同樣的想法,你的代碼。然後,您可以在Google用戶信息API中使用OAuth令牌,如Using OAuth 2.0 for Login中所述,以驗證電子郵件並獲取用戶名。

+0

非常感謝你這個答案。我一定會嘗試你的解決方案。這是前一段時間,我想我設法做到這一點,但我現在會嘗試這種方法。這似乎很容易。 – TheJohnny 2012-06-06 16:00:11

+0

你試過了@TheJohnny,bocoz我也面臨同樣的問題,我的應用程序也是......... – 2012-09-26 07:36:11

+0

@Darshan Computing我已經看到使用瀏覽器獲取auth訪問權限。即用戶可以使用任何帳號,而不是在他的手機上登錄的帳號。就像在彩票應用程序等。我如何實現這一目標? – 2013-07-19 12:14:57

相關問題