2014-03-13 84 views
2

我有一個從谷歌API獲取oauth 2.0令牌的問題。我目前正在編寫應用程序android,我想要有三種方法登錄 - 通過Facebook(完成),通過自定義oauth 2.0提供程序(也完成)和通過谷歌加 - 它使我很多問題。 我需要在設備上獲取訪問令牌,並將其傳遞給後端應用程序。如何從android中獲取谷歌加API的oauth 2.0令牌?

我嘗試使用GoogleApiClient(PlusClient已棄用 - 通過 http://developer.android.com/reference/com/google/android/gms/plus/PlusClient.html),但看不到像getAccessToken或類似的方法。

目前我嘗試使用socialauth庫,但我堅持,由於缺乏文件(這裏是一些代碼)

private SocialAuthAdapter mSocialAdapter; 
... in onCreate() 
mSocialAdapter = new SocialAuthAdapter(new GooglePlusSocialAuthListener()); 
try { 
    mSocialAdapter.addConfig(Provider.GOOGLEPLUS, key_from_google_developers_console, secret, 
    "https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email"); 
    mSocialAdapter.addCallBack(Provider.GOOGLEPLUS, 
    "http://localhost:3000/api/auth/gplus/callback"); 
} 
catch (Exception e) { 
    e.printStackTrace(); 
} 

mSocialAdapter.authorize(LoginActivity.this, Provider.GOOGLEPLUS); 
Log.e("TOKEN HERE ", mSocialAdapter.getCurrentProvider().getAccessGrant().getKey()); 

任何人可以幫助我得到這個令牌?無論它是通過socialauth還是通過GoogleApiClient。

回答

5

對社交認證沒有任何線索,但爲了從Google Play服務獲取令牌,您實際上使用了另一個類GoogleAuthUtil。

我把這個要點上https://gist.github.com/ianbarber/9607551 - 相關部分:

String scopes = "oauth2:profile email"; // magic string! oauth2: followed by space sep scopes. 
String token = null; 
try { 
    token = GoogleAuthUtil.getToken(getApplicationContext(), accountName, scopes); 
} catch (IOException e) { 
    Log.e(TAG, e.getMessage()); 
} catch (UserRecoverableAuthException e) { 
    startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED); 
} catch (GoogleAuthException e) { 
    Log.e(TAG, e.getMessage()); 
} 
return token; 

帳戶名稱可以從GoogleApiClient Plus.Account API http://developer.android.com/reference/com/google/android/gms/plus/Account.html

+0

可以得到這正是我需要的!不能相信這是如此簡單。謝謝! – Zkart

相關問題