Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to get Refresh Token by Google Sign-In API?

Currently, I am working on the application where user able to login with Google. As part of the login process, we need to send Google ACCESS TOKEN and REFRESH TOKEN to server end.

I am retrieving access token by the following method,

        mAccountName = googleSignInAccount.getEmail();
        String scopes = "oauth2:profile email";
        String token = null;
        try {
            token = GoogleAuthUtil.getToken(activity.getApplicationContext(), mAccountName, scopes);
        } catch (IOException e) {
            Logger.eLog(TAG, e.getMessage());
        }

GoogleAuthUtil class from which I am accessing access token don't have a function for refresh token. So how to access Refresh Token? Thanks in advance!

like image 955
Swapnil Sonar Avatar asked Feb 02 '16 13:02

Swapnil Sonar


People also ask

How do I use API refresh token?

To use the refresh token, make a POST request to the service's token endpoint with grant_type=refresh_token , and include the refresh token as well as the client credentials if required.


2 Answers

You should use the server auth code flow via Auth.GOOGLE_SIGN_IN_API: get an server auth code on Android client, send to your server, server exchanges the code for refresh and access token (with a secret). There are more details in this blog post as well.

Also, if you are using GoogleAuthUtil.getToken for access token now, you do want to check out this Google Sign-In best practice blog post to see how to migrate to the recommended flow to ensure security and best UX.

like image 181
Isabella Chen Avatar answered Sep 21 '22 00:09

Isabella Chen


I think you need to try this code in AsyncTask like below.

private class RetrieveTokenTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String accountName = params[0];
        String scopes = "oauth2:profile email";
        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);
    //REQ_SIGN_IN_REQUIRED = 55664;
        } catch (GoogleAuthException e) {
            Log.e(TAG, e.getMessage());
        }
        return token;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.i("AccessToken",s);
    }
}

Then call AsyncTask like below to get Access Token:

...    
new RetrieveTokenTask().execute(mAccountName);

Check here. I hope it's help you.

like image 30
pRaNaY Avatar answered Sep 18 '22 00:09

pRaNaY