Android:如何通过Google登录API获取刷新令牌?

时间:2016-02-02 13:12:27

标签: android google-api google-play-services access-token google-signin

目前,我正在开发用户可以使用Google登录的应用程序。作为登录过程的一部分,我们需要将Google ACCESS TOKEN和REFRESH TOKEN发送到服务器端。

我正在通过以下方法检索访问令牌,

        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类没有刷新令牌功能。那么如何访问Refresh Token呢?提前谢谢!

2 个答案:

答案 0 :(得分:9)

您应该使用server auth code flow via Auth.GOOGLE_SIGN_IN_API:在Android客户端上获取服务器验证码,发送到您的服务器,服务器交换代码以进行刷新和访问令牌(带有秘密)。此blog post中还有更多详细信息。

此外,如果您现在使用GoogleAuthUtil.getToken作为访问令牌,您需要查看此Google Sign-In best practice blog post以了解如何迁移到建议的流程以确保安全性和最佳用户体验。

答案 1 :(得分:2)

我认为您需要在AsyncTask中尝试此代码,如下所示。

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

然后如下所示调用AsyncTask以获取访问令牌:

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

检查here。 我希望它对你有帮助。