我有以下 JS 代码来获取与 Google 的 OAuth2 流的身份验证代码:
gapi.client.init({
apiKey: apiKey,
clientId: clientId,
scope: scopes
});
//...
gapi.auth2.getAuthInstance().grantOfflineAccess({
scope: 'email profile'
})
.then(function(response) {
if (response && !response.error) {
// google authentication succeed, now post data to server.
$.ajax({
type: 'POST',
url: "my_url",
data: {
code: response.code
},
success: function(data) {
//...
},
error: function(er) {
console.log(er);
}
});
} else {
console.log('google authentication failed');
console.log(response)
}
});
POST 是使用 Ruby on Rails 应用程序的代码制作的,在该应用程序中我使用Signet
gem 来处理身份验证流程,我按照以下方式对其进行初始化:
@client = Signet::OAuth2::Client.new(
:authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
:token_credential_uri => 'https://www.googleapis.com/oauth2/v3/token',
:client_id => GCAL_CLIENT_KEY,
:client_secret => GCAL_CLIENT_SECRET,
:scope => 'email profile',
additional_parameters: {
"access_type" => "offline",
"include_granted_scopes" => "true"
}
)
然后尝试获取访问令牌:
@client.code = auth_code
@client.fetch_access_token!
但得到以下异常:
#<Signet::AuthorizationError: Authorization failed. Server message:
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}>
还尝试使用 HTTP/REST 调用与请求正文,如此处https://www.googleapis.com/oauth2/v4/token
所述。但同样的回应 - 无效的grant_type