使用GoogleAuth.grantOfflineAccess在服务器上进行身份验证时发生Redirect_URI错误
我正在尝试使用概述在https://developers.google.com/identity/sign-in/web/server-side-flow处的授权流程。 我创建了如下所示的证书...没有指定授权重定向URI,因为doc指示:“授权重定向URI字段不需要值,重定向URI不用于JavaScript API。使用GoogleAuth.grantOfflineAccess在服务器上进行身份验证时发生Redirect_URI错误
启动的授权的代码是: Client按钮和回调:
<script>
$('#signinButton').click(function() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.grantOfflineAccess().then(signInCallback);
});
function signInCallback(authResult) {
console.log('sending to server');
if (authResult['code']) {
// Send the code to the server
$.ajax({
type: 'POST',
url: 'CheckAuth',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
服务器侧(CheckAuth方法来创建从AUTH码,它通过JavaScript回调正确接收凭证):
private Credential authorize() throws Exception {
// load client secrets
InputStream is = new FileInputStream(clientSecretsPath_);
InputStreamReader isr = new InputStreamReader(is);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, isr);
String redirect_URI = "";
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
httpTransport, JSON_FACTORY,
"https://www.googleapis.com/oauth2/v4/token",
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
token_,
redirect_URI)
.execute();
String accessToken = tokenResponse.getAccessToken();
// Use access token to call API
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
return credential;
}
流程正常工作,直到我的服务器尝试交换令牌响应的授权码(GoogleAuthorizationCodeTokenRequest.execute())... auth服务器返回的点:
400 Bad Request
{
"error" : "invalid_request",
"error_description" : "Missing parameter: redirect_uri"
}
鉴于此错误,我在javascript中的auth实例中查看了debug,并注意到它指示的是redirect_uri。然后,我更新了我的Google凭据,并在授权重定向URI(它是访问javascript的URL,因为auth服务器正确返回到指定的JavaScript回调)中指定了该URI。随着GoogleAuthorizationCodeTokenRequest的(字符串REDIRECT_URI =“http://example.com:8080/JavascriptLocation”)的实例指定更新的证书和URI,错误就变成了:
400 Bad Request
{
"error" : "redirect_uri_mismatch",
"error_description" : "Bad Request"
}
我已经追踪一路贯穿到实际的HttpRequest的AUTH服务器(www.googleapis.com/oauth2/v4/token),并且无法分辨它正在查找的是什么redirect_uri。
有没有人知道这种情况下redirect_uri的值应该是多少(使用grantOfflineAccess()时)?我很高兴发布更多的代码,如果这是有帮助的...只是不想泛滥的页面。谢谢。
在发布问题后发现了对“postmessage”的引用......使用它作为服务器端的redirect_URI似乎从auth服务器生成了成功的响应。所以...在下面的代码中设置redirect_URI =“postmessage”似乎在这种情况下工作。
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
httpTransport, JSON_FACTORY,
"https://www.googleapis.com/oauth2/v4/token",
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
token_,
redirect_URI)
.execute();