javascript - Google 通过 OAuth2 身份验证从 JavaScript 客户端联系 API 问题

标签 javascript oauth-2.0 google-contacts-api

现在已经为此苦苦挣扎了好几个小时,文档似乎很糟糕。基本上,我正在尝试使用 Portable Contacts API 获取对 OAuth2 身份验证用户联系人的读取权限。或完全成熟的Contacts API .谷歌有 recently开始allowing OAuth2 .

我可以通过 Contacts API 访问用户的联系人,方法是首先让用户使用以下范围进行身份验证:“https://www.google.com/m8/feeds”。然后我可以使用 jQuery 检索他们的前 25 个联系人(显示的代码是 CoffeeScript )

$.ajax
  url: "https://www.google.com/m8/feeds/contacts/default/full"
  dataType: 'jsonp'
  data: { access_token: token, alt: 'json-in-script' }
  success: (data, status) ->
    console.log "The returned data", data

这行得通,我得到了 JSON 数据。然而,几乎令人难以置信的是,Google 提供的唯一联系人顺序(据我所知)是“lastmodified”。 '(认真的 wtf?)。我需要更像“顶级 friend ”或“最受欢迎”的东西。

这恰好是 Google 可移植联系人 API can do 的东西, (耶!)。当然,我似乎无法获得成功的工作请求。

首先,我通过单击此链接(注意范围:“https://www-opensocial.googleusercontent.com/api/people”)让用户使用可移植联系人 API 进行身份验证

<a href="https://accounts.google.com/o/oauth2/authclient_id=457681297736.apps.googleusercontent.com&response_type=token&redirect_uri=http://localhost:3000/team&scope=https://www-opensocial.googleusercontent.com/api/people">Import Google Contacts</a>

这很好用,我得到了传回的访问 token 。

接下来我尝试向可移植联系人 API 发送 ajax 请求

$.ajax
  url: "https://www-opensocial.googleusercontent.com/api/people/@me/@all"
  dataType: 'jsonp'
  data: { access_token: token, alt: 'json-in-script' }
  success: (data, status) ->
    console.log "The returned data", data

但这会返回 403 错误

403 (The currently logged in user and/or the gadget requesting data, does not have access to people data.

知道我做错了什么吗?

附录
我找到了 this bug report在 Google OAuth2 论坛中建议我们在使用 Portable Contacts API 时需要设置授权 header 。所以我试过这样:

$.ajax
  url: "https://www-opensocial.googleusercontent.com/api/people/@me/@all"
  dataType: 'jsonp'
  data: { access_token: token, alt: 'json-in-script' }
  beforeSend: (xhr) ->
    xhr.setRequestHeader "Authorization", "OAuth #{token}"
  data: { access_token: token }
  success: (data, status) ->
    console.log "The returned data", data

但这让我得到了同样的 403 错误:

403 (The currently logged in user and/or the gadget requesting data, does not have access to people data

最佳答案

问题是您显然无法在 JSONP 请求上设置请求 header 。查看 this question 上的答案获取更多信息。

据我所知,备选方案是:

  1. 使用Google Contacts API JS library .这只使用谷歌自己认为不好的 AuthSub。我宁愿不这样做。我与之交互的所有其他服务都使用 OAuth2。
  2. 使用我链接到的 SO 问题中提到的新的 Level 2 Ajax 和 XDomainRequest 标准。然而,他们会带来自己的问题。整体听起来很乱。它在旧版浏览器中不起作用,我必须进行大量功能检测等。我什至不知道 API 是否支持这些功能。
  3. 全部在服务器上完成。这也不是很理想。不够完美的用户体验。

谷歌不应该这么难。

关于javascript - Google 通过 OAuth2 身份验证从 JavaScript 客户端联系 API 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7400575/

相关文章:

javascript - 如何将ajax数据传递给react中的组件

javascript - (?:x) character? 有什么意义

laravel - OAuth 还是 JWT?使用哪一个以及为什么?

JavaScript 使用 "new"

具有固定导航栏偏移量的 Javascript 平滑滚动

google-plus - Google Contacts API 是否支持高分辨率图片?

python + appengine + oauth2 + 谷歌联系人 api

javascript - 使用 angularjs 导入 Google 联系人

python-2.7 - 使用requests_oauthlib访问OAuth2网页

rest - 具有预配置授权的 OAuth 安全性