Google oauth 400 响应:请求的资源上不存在 'Access-Control-Allow-Origin' header

Google oauth 400 response: No 'Access-Control-Allow-Origin' header is present on the requested resource

我正在尝试从 client-side javascript 向具有 google 日历范围的 google oauth 端点 (https://accounts.google.com/o/oauth2/v2/auth) 发出请求。问题是,我不能使用 google 的 javascript 客户端,因为我实际上使用的是 webpack,我不想在我的外部单独包含一个 javascript 脚本bundle.js.

因此,我使用 axios (https://github.com/mzabriskie/axios) 将 HTTP GET 发送到上述令牌端点。我的请求如下所示:

https://accounts.google.com/o/oauth2/v2/auth?response_type=token&client_id={client id here}&nonce=c8ef445540186351d9108ad64d7a5b65&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar

我使用 crypto-js 库的 MD5 函数生成了随机数。这是请求 headers:

Accept:application/json, text/plain, */*
Origin:http://localhost:8000
Referer:http://localhost:8000/admin
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36

我从 google 得到的回复是这样的:

alt-svc:quic=":443"; ma=2592000; v="32,31,30,29,28,27,26,25"
alternate-protocol:443:quic
cache-control:no-cache, no-store, max-age=0, must-revalidate
content-encoding:gzip
content-type:text/html; charset=utf-8
date:Mon, 18 Apr 2016 07:16:21 GMT
expires:Fri, 01 Jan 1990 00:00:00 GMT
pragma:no-cache
server:GSE
status:400
x-content-type-options:nosniff
x-frame-options:SAMEORIGIN
x-xss-protection:1; mode=block

我在我的 chrome devtools 控制台中看到了这个日志:

XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/v2/auth?response_type=token&client_id={client id here}&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 400.

我已确保在我的 google 应用程序控制台中,在相应的客户端 ID 下,我添加了 http://localhost:8000 to the "Authorized Javascript Origins" field, and I've made sure to enable authorization for the google calendar api. I've read that the web client implicit auth flow doesn't use the redirect uri, but I've tried filling that out regardless (I've tried the values http://localhost:8000 and http://localhost:8000/admin,这是我发送请求的页面)。花了几个小时在谷歌上搜索,我没有发现任何迹象表明我正在做的事情不应该起作用。

所以我的问题是,如果我允许 http://localhost:8000 作为我的客户端 ID 的授权来源,为什么我仍然无法向它发送请求(尽管是通过 javascript)身份验证端点?

我认为您应该将浏览器重定向到这个 oauth2 端点,而不是仅仅尝试向它发出 ajax 请求。

https://developers.google.com/identity/protocols/OAuth2UserAgent#overview