【发布时间】:2018-10-14 01:58:35
【问题描述】:
我正在尝试通过 oAuth2 机制为用户获取 Google 联系人。我正在关注本教程 - https://developers.google.com/identity/sign-in/web/server-side-flow
我有在页面加载时调用 start() 的 javascript 代码 -
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。
【问题讨论】:
-
解决了吗?
-
是的。接受了答案。
-
我也在关注相同的 url:developers.google.com/identity/sign-in/web/server-side-flow 仍然在获取 redirect_uri_mismatch 为了在本地测试,我在 google api 控制台中添加了“http:localhost:8080/oauth2callback”。你能帮助你解决这个问题吗?我使用相同的 java 代码
-
您注册的重定向 uri 和您在请求中发送的必须相同
标签: java google-oauth google-contacts-api google-oauth-java-client