获取 Google oAuth2 访问令牌时出现问题 - 重定向 URI 不匹配

Problems while getting Google oAuth2 access token - Redirect Uri Mismatch

我正在尝试通过 oAuth2 机制为用户获取 google 联系人。我正在学习本教程 - https://developers.google.com/identity/sign-in/web/server-side-flow

我有 java在页面加载时调用 start() 的脚本代码 -

function start() {
  gapi.load('auth2', function() {
    auth2 = gapi.auth2.init({
      client_id: 'SOME_CLEINT_ID',
      scope: 'https://www.googleapis.com/auth/contacts.readonly'
    });
  });
}

auth2.grantOfflineAccess().then(signInCallback);

然后-

function signInCallback(authResult) {
    if (authResult['code']) {
        var callback = function(data){
            data = JSON.parse(data);
            console.log(data);
        };
        callAjax({action: 'saveGmailAuth', gaccesscode: authResult['code']}, callback, true);
    } else {
        // There was an error.
    }
}

此前端代码调用我的后端 Java web servlet,它试图获取访问令牌 -

String authCode = request.getParameter("gaccesscode");
        String REDIRECT_URI = "";
        String CLIENT_SECRET_FILE = "G:/eclipse_proj/GoogleContacts/CLIENT_JSON_FILE.json";
        GoogleClientSecrets clientSecrets;
        try {
            clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(),
                    new FileReader(CLIENT_SECRET_FILE));
            REDIRECT_URI = clientSecrets.getDetails().getRedirectUris().get(0);
            GoogleAuthorizationCodeTokenRequest tokenRequest = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(),
                    JacksonFactory.getDefaultInstance(), "https://www.googleapis.com/oauth2/v3/token",
                    clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), authCode,
                    REDIRECT_URI);
            GoogleTokenResponse tokenResponse = tokenRequest.execute();
            String accessToken = tokenResponse.getAccessToken();
            GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

每次我尝试此 java 代码时,每次它都会在 tokenRequest.execute() -

处给我错误
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "redirect_uri_mismatch",
  "error_description" : "Bad Request"
}

将 REDIRECT_URI 作为空字符串,它会给出另一个错误提示 - redirect_uri_not_provided.

我用“https://www.googleapis.com/oauth2/v3/token”和“https://www.googleapis.com/oauth2/v4/token”都试过了

我需要帮助来解决这个问题。我在这里做错了什么?

我的重定向 URI 是 - http://localhost:8080/GoogleContacts/Callback 在 json 文件和 oauth2 的开发者控制台中。

对于 redirect_uri 使用 Google API,请转到您的 Google 开发控制台并按原样键入:

//you can use any port you want
http:localhost:8080/oauth2callback

oauth2callback 是关键成分。