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

元气小坏坏 提交于 2019-12-18 11:53:54

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/35154509/android-how-to-get-refresh-token-by-google-sign-in-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!