获取Gmail API访问权限和ID令牌,但刷新令牌为NULL

时间:2017-06-04 18:50:24

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

关注https://developers.google.com/identity/sign-in/web/server-side-flow从JavaScript获取授权代码并将其传递到服务器端后,我们确实获得了访问令牌(和ID令牌),但没有获得所需的刷新令牌。

周围有很多帖子但尚未解决。

有关如何获取刷新令牌的任何建议吗?

谢谢!

    private String getResponseToken(GoogleClientSecrets clientSecrets,
                                                 String authCode) throws IOException {
        try {
            GoogleTokenResponse tokenResponse =
                    new GoogleAuthorizationCodeTokenRequest(
                            new NetHttpTransport(),
                            JacksonFactory.getDefaultInstance(),
                            "https://www.googleapis.com/oauth2/v4/token",
//                        "https://accounts.google.com/o/oauth2/token",
                            clientSecrets.getDetails().getClientId(),
                            clientSecrets.getDetails().getClientSecret(),

                            authCode, //NOTE: was received from JavaScript client

                            "postmessage" //TODO: what's this? 
                            ).execute();
            String accessToken = tokenResponse.getAccessToken();
            String idToken = tokenResponse.getIdToken();

            //TODO: not getting a refresh token... why?!
            String refreshToken = tokenResponse.getRefreshToken();
            Boolean hasRefreshToken = new Boolean(!(refreshToken == null));
            LOGGER.warn("received refresh token: {}", hasRefreshToken);

            LOGGER.debug("accessToken: {}, refreshToken: {}, idToken: {}", accessToken, refreshToken, idToken);
            return accessToken;
        }catch (TokenResponseException tre){...}

3 个答案:

答案 0 :(得分:2)

Gmail API仅在您首次要求用户权限时才提供刷新令牌。 (至少这是我发生的事情)。

转到:https://myaccount.google.com/permissions?pli=1,删除对您应用的授权并运行您的代码。您应该收到刷新令牌。

答案 1 :(得分:0)

你应该添加

  1. AccessType ="离线"
  2. 你需要调用函数

    new GoogleAuthorizationCodeRequestUrl(...).setAccessType("offline") 
    

    或其他语法:

    var authReq = new GoogleAuthorizationCodeRequestUrl(new Uri(GoogleAuthConsts.AuthorizationUrl)) { 
        RedirectUri = Callback, 
        ClientId = ClientId, 
        AccessType = "offline", 
        Scope = string.Join(" ", new[] { Scopes... }), 
        ApprovalPrompt = "force" 
    };
    
    在Fiddler中你应该看到以下请求:

    https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/webmasters&redirect_uri=http://mywebsite.com/google/scapi/callback/&response_type=code&client_id=xxx& ACCESS_TYPE =离线

    另见here

    可以找到有关setAccessType的更多详细信息here

答案 2 :(得分:0)

在找到如何在后端使用Google API之后(文档有点偏......),通过调整参数在FrontEnd端解决了这个问题:

grantOfflineAccess({ - 提示:' select_account' +提示:'同意'

HTH