2014-03-13 87 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

相关问题