java - 在重新验证用于使用 Oauth 发送电子邮件的 Gmail API 时,refresh_token 为 null

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

我正在使用 Scribe for oauth 来获取 auth_code 的 access_token 和 refresh_token。它对于第一次身份验证效果很好。 当我在应用程序中禁用凭据时, token 仍然存在于我的应用程序的 Gmail 连接应用程序中。 当我重新启用 oauth 时,我仅获得新 auth_code 的有效新 access_token。但refresh_token为空。 我尝试使用 oauthplayground 复制相同的内容,在那里我可以看到有效的刷新和访问 token ,而 Playground token 仍然存在于 Google 连接的应用程序中。

这是我使用 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());

谁能帮我解决我哪里出错了? 感谢您花时间查看此问题。

最佳答案

重新认证时需要设置这些参数 access_type=offlineapproval_prompt=force 然后您将收到 refresh_token

下面是一个示例 URL 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

关于java - 在重新验证用于使用 Oauth 发送电子邮件的 Gmail API 时,refresh_token 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40974619/

相关文章:

javascript - iOS 8 在 OAuth 的 401 上显示基本身份验证的弹出窗口

java - 如何更改谷歌 token 过期时间?

android 中 java.text.parseeException 不可解析的日期

java - 使用文件java代码中的arraylist进行登录?

java - 如何在关系数据库中存储带有 child 的链接树?

Nginx 和 Oauth2-proxy : After logging in with Google, 重定向回 Oauth 登录页面

javascript - 使用 axios 获取访问 token

google-apps-script - 尝试授权脚本时出现 "Sign in with Google temporarily disabled for this app"错误

python - 在不离开页面的情况下使用 django-allauth 进行社交登录

java - 使用 ListView 滚动布局 android