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

时间:2018-05-03 17:01:17

标签: java google-oauth google-oauth2 google-contacts google-oauth-java-client

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

我有javascript代码,在pageload上调用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在json文件和oauth2的开发者控制台中都是 - http://localhost:8080/GoogleContacts/Callback

1 个答案:

答案 0 :(得分:1)

对于使用Google API的redirect_uri,请转到您的Google Dev控制台并输入您所看到的内容:

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

oauth2callback 是关键因素。