我正在尝试从客户端javascript向具有Google日历范围的google oauth端点(https://accounts.google.com/o/oauth2/v2/auth)发出请求。问题是,我不能使用Google的javascript客户端,因为我实际上是在使用webpack,并且我不想在bundle.js之外单独包含javascript脚本。
因此,我改为使用axios(https://github.com/mzabriskie/axios)使HTTP GET到达上述 token 端点。这是我的要求:
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函数生成了随机数。以下是请求 header :
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添加到“Authorized Javascript Origins”字段中,并且确保启用了Google日历api的授权。我已经了解到Web客户端隐式身份验证流不使用重定向uri,但是无论如何我都尝试填写(我尝试了http://localhost:8000和http://localhost:8000/admin值,这是我从其发送请求的页面)。花了几个小时的时间进行了搜索,但我没有发现任何暗示我正在做的事情不起作用的建议。
所以我的问题是,如果我允许http://localhost:8000作为我的客户ID的授权来源,为什么我仍然无法向该auth端点发送请求(尽管通过javascript)?
最佳答案
我相信您应该将浏览器重定向到此oauth2终结点,而不是仅尝试向其发出ajax请求。
https://developers.google.com/identity/protocols/OAuth2UserAgent#overview