我正在设置漂亮的Rails API,我需要从Google接收一个oauth2令牌,然后使用它来获取用户的基本信息(全名,电子邮件等)。
令牌是由移动应用生成的,并发送到API。
以下代码用于获取用户的电子邮件,但不能获取其他字段
def google(auth) require 'google/apis/oauth2_v2' oauth2 = Google::Apis::Oauth2V2::Oauth2Service.new google_profile = oauth2.tokeninfo(id_token: auth) end
我已尝试通过以下方式获取调用userinfo的用户信息:
google_profile = oauth2.get_userinfo google_profile = oauth2.get_userinfo_v2
但是他们都不起作用,我得到了
Google::Apis::AuthorizationError (Unauthorized)
我似乎无法找到一种方法来配置gem以正确配置授权密钥
oauth2.key='AIz...ryg'
也尝试使用这样的auth json:
{ "web": { "client_id":"xxx.apps.googleusercontent.com", "project_id":"...", "auth_uri":"https://accounts.google.com/o/oauth2/auth", "token_uri":"https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs", "client_secret":"aZ...sl" } }
但是我总是会遇到同样的例外。调用
ex.body
返回
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"domain": "global",
"reason": "unauthorized"
}
],
"status": "UNAUTHENTICATED"
}
}
我正在设置一个漂亮的Rails API,我需要从Google接收一个oauth2令牌,然后使用它来获取用户的基本信息(全名,电子邮件等)。令牌是由移动应用生成的...
完成这项工作(对C&P进行了https://gist.github.com/skycocker/ba67e6756131fb43cf4963e024158be1的细微修改):