在重新验证使用Oauth发送电子邮件的Gmail API时,将refresh_token设置为null

时间:2016-12-05 12:47:00

标签: java oauth-2.0 google-oauth gmail-api

我正在使用Scribe for oauth获取auth_code的access_token和refresh_token。它适用于第一次身份验证。 当我在我的应用程序中禁用凭据时,代码仍然存在于我的应用程序的Gmail连接应用程序中。 当我重新启用oauth时,我只获得新的auth_code的有效新access_token。但是refresh_token为null。 我尝试使用oauthplayground复制相同内容,在那里我可以看到有效的刷新和访问令牌,而游戏机令牌仍然存在于谷歌连接的应用程序中。

这是我用scribe-1.3.0 API实现的代码

    OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, "https://accounts.google.com/o/oauth2/token");

    oAuthRequest.addBodyParameter("client_id", SMTP_OAUTH_CLIENT_ID);
    oAuthRequest.addBodyParameter("client_secret", SMTP_OAUTH_CLIENT_SECRET);

    oAuthRequest.addBodyParameter("scope", scope);
    oAuthRequest.addBodyParameter("redirect_uri", GoogleApi.getRedirectURL());

    oAuthRequest.addBodyParameter("code", authCode);
    oAuthRequest.addBodyParameter("grant_type", "authorization_code");

    Response response = oAuthRequest.send();

以下是与googleapi-client-1.20一起尝试的类似代码,结果仍然相同。

        GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
                new NetHttpTransport(), 
                new JacksonFactory(), 
                SMTP_OAUTH_CLIENT_ID, SMTP_OAUTH_CLIENT_SECRET, 
                authCode, 
                GoogleApi.getRedirectURL())
                    .execute();

        Credential gcredential = new GoogleCredential
                .Builder()
                .setTransport(new NetHttpTransport.Builder().build())
                .setJsonFactory(new JacksonFactory())
                .setClientSecrets(SMTP_OAUTH_CLIENT_ID, SMTP_OAUTH_CLIENT_SECRET)
                .build()
                .setFromTokenResponse(tokenResponse);

        gcredential.refreshToken();

        System.out.println(gcredential.getRefreshToken());

任何人都可以在我出错的地方帮助我吗? 感谢您抽出时间查看此问题。

1 个答案:

答案 0 :(得分:1)

重新进行身份验证时,您需要设置这些参数 access_type=offlineapproval_prompt=force 然后你会收到refresh_token

以下是示例网址 https://accounts.google.com/o/oauth2/auth?client_id=CLIENT_ID&scope=SCOPE&redirect_uri=REDIRECT_URL&response_type=code&access_type=offline&approval_prompt=force