【发布时间】:2017-11-06 05:57:54
【问题描述】:
我正在尝试使用https://developers.google.com/identity/sign-in/web/server-side-flow 中概述的授权流程。 我已经按照指示创建了凭据...没有指定授权重定向 URI,如文档所示:“授权重定向 URI 字段不需要值。重定向 URI 不与 JavaScript API 一起使用。”
启动授权的代码是: 客户端按钮和回调:
<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 方法从身份验证代码创建凭据,它通过 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 实例的调试,并注意到它指示的是 redirect_uri。然后,我更新了我的 google 凭据并在授权重定向 URI 中指定了该 URI(它是访问 javascript 的 URL,因为身份验证服务器正确返回到指定的 javascript 回调)。使用更新的凭据和在 GoogleAuthorizationCodeTokenRequest 实例化中指定的 URI (String redirect_URI = "http://example.com:8080/JavascriptLocation";),则错误变为:
400 Bad Request
{
"error" : "redirect_uri_mismatch",
"error_description" : "Bad Request"
}
我一直跟踪到身份验证服务器 (www.googleapis.com/oauth2/v4/token) 的实际 HttpRequest,但无法确定它在寻找什么 redirect_uri。
有谁知道在这种情况下redirect_uri 的值应该是多少(使用grantOfflineAccess() 时)?我很高兴发布更多代码,如果这有帮助的话......只是不想淹没页面。谢谢。
【问题讨论】: