Domanda

I have a problem with obtaining oauth 2.0 token from google API. I am currently writing app for android, where I want to have three methods of signing in - via facebook (done), via custom oauth 2.0 provider (also done) and via google plus - it makes many problems for me. I need to get access token on the device, and pass it further to backend application.

I tried using GoogleApiClient (PlusClient is deprecated - via http://developer.android.com/reference/com/google/android/gms/plus/PlusClient.html), but cannot see a method like getAccessToken or something similar.

Currently i try to use socialauth library, but I'm stuck due to lack of documentation (here is some code)

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());

Can anybody help me to get this token? It doesn't matter if it is via socialauth or via GoogleApiClient.

È stato utile?

Soluzione

No clue on social auth, but to get the token from Google Play services you actually use another class, GoogleAuthUtil.

I put a gist of this on https://gist.github.com/ianbarber/9607551 - the relevant part:

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;

The account name can be got from the GoogleApiClient Plus.Account API http://developer.android.com/reference/com/google/android/gms/plus/Account.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top