2

我有一个实施了 Google OAUTH2 并且可以正常工作的 Rails 网站。

我们正在开发一个 iOS 应用程序,它将使用 API 与我的 Web 服务器通信。某些 API 需要对用户进行身份验证。这个想法是,iOS 应用程序在设备上使用 OAUTH2 对用户进行身份验证,然后通过 SSL 将令牌从设备发送到 Web 作为身份验证。我需要网站来验证令牌。

在 Google API 控制台中,我添加了 iPhone 设备的客户端 ID,并通过以下方式获取了访问令牌:

https://accounts.google.com/o/oauth2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&
redirect_uri=urn:ietf:wg:oauth:2.0:oob&
response_type=code&
client_id={my client id}

然后,我将令牌传递给我的站点。在我的网站上,我通过以下方式验证令牌:

google = OmniAuth::Strategies::GoogleOauth2.new(ENV['GOOGLE_API_KEY'],['GOOGLE_CLIENT_API_SECRET'])
client = OAuth2::Client.new(ENV['GOOGLE_API_KEY'],['GOOGLE_CLIENT_API_SECRET'], google.options.client_options)
access_token = OAuth2::AccessToken.new(client, params[:token], google.options.access_token_options || {})
google.access_token = access_token
google.auth_hash

当我尝试时auth_hash,返回以下错误:

 {
  "error": {
   "errors": [
    {
     "domain": "global",
     "reason": "authError",
     "message": "Invalid Credentials",
     "locationType": "header",
     "location": "Authorization"
    }
   ],
   "code": 401,
   "message": "Invalid Credentials"
  }
 }

从这里开始,我不知道为什么我指定了无效的凭据。

ENV['GOOGLE_API_KEY']指向与网站相同的 API 密钥,并ENV['GOOGLE_CLIENT_API_SECRET']指向 iOS 客户端的密钥。

4

1 回答 1

2

我想,我上面使用的 URL 给了我一个access token. 实际上,它返回给我一个authorization code(然后可以用来获取一个access token)。

解决方案是将 , 换成authorization code,access token然后我可以传递令牌并使用它。

authorization code在 Google 网站上,an和 an之间的区别access token有些模糊,但您可以在此处阅读有关如何交换它们的信息: https ://developers.google.com/accounts/docs/OAuth2WebServer

于 2012-08-13T02:32:06.087 回答