Google oauth 400响应:请求的资源上没有"Access-Control-Allow-Origin"标头

And*_*hen 5 javascript google-api google-oauth2

我正在尝试使用Google日历范围向客户端javascript向google oauth端点(https://accounts.google.com/o/oauth2/v2/auth)发出请求.事实是,我不能使用谷歌的JavaScript客户端,因为我实际上使用的是webpack,而且我不想在我的bundle.js之外单独包含一个javascript脚本.

因此,我使用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
Run Code Online (Sandbox Code Playgroud)

我使用crypto-js库的MD5函数生成了nonce.以下是请求标头:

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
Run Code Online (Sandbox Code Playgroud)

我从谷歌得到的回应如下:

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
Run Code Online (Sandbox Code Playgroud)

我在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.
Run Code Online (Sandbox Code Playgroud)

我确保在我的谷歌应用程序控制台中,在相应的客户端ID下,我已将http:// localhost:8000添加到"授权的Javascript起源"字段中,并且我已确保为Google启用授权日历api.我已经读过Web客户端隐式身份验证流程不使用重定向uri,但我已经尝试填写它了(我已经尝试了值http:// localhost:8000http:// localhost:8000/admin,这是我发送请求的页面.花了几个小时来搜索这个,我没有发现任何暗示我正在做的事不应该工作.

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

Wik*_*hla 6

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

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