我有以下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
您尚未在 Signet gem 初始化中设置redirect_uri,似乎 Signet 依靠它来grant_type设置为 authorization_code:https://github.com/google/signet/blob/621515ddeec1dfb6aef662cdfaca7ab30e90e5a1/lib/signet/oauth_2/client.rb#L834