我正在尝试使用oauth2从JavaScript客户端访问一些Google API。我成功地让用户验证了请求,但是在运行下面的代码时存在一些意外行为,我想理解。当我第一次点击“授权”按钮时,结果是:

'[{“错误”:{“代码”:401,“消息”:“需要”,“数据”:[{“域”:“全局”,“原因”:“必填”,“消息“:”登录需要“,”位置“:”标题“,”位置“:”授权“}]}”id“:”gapirpc“}]'

在第二次点击中,结果是

[{“id”:“gapirpc”,“结果”:{“ID”:“1115793426680xxxx”,“电子邮件”:“xxxxx@gmail.com”,“验证_email”:true}}]

这是我测试的页面的代码

<div id='sign in'>
    <button onclick="init();">Authorize</button>
</div>
<p id="output">hello</p>

<script type="text/javascript">
    function init() {
        document.getElementById('output').innerHTML='loading oauth2 api'
        gapi.client.load('oauth2', 'v2', auth);
    }

    function auth() {
        var config = {
            client_id: '2264xxxxx-odt0g7jn8vspa3ot9ogjxxxxxxxxx.apps.googleusercontent.com',
            scope: 'https://www.googleapis.com/auth/userinfo.email',
            immediate:true
        };
        document.getElementById('output').innerHTML='authorizing'
        gapi.auth.authorize(config, authed());
    }

    function authed() {
        document.getElementById('output').innerHTML='authorized'
        var request = gapi.client.oauth2.userinfo.get().execute(
            function(resp, raw) {
                document.getElementById('output').innerHTML=raw
            }
        );
    }
 </script>
<script src="https://apis.google.com/js/client.js"></script>
<!--<script src="https://apis.google.com/js/client.js?onload=init"></script>-->
.

可以请解释为什么我在第一次执行代码时会获得“登录需要”以及第二个执行中成功的身份验证?

有帮助吗?

解决方案

由于在对Gapi.auth.auth.authorize中的“Authed”中的“Authed”中的括号之后,在调用Gapi.auth.authorize之前,请立即运行Authed()回调。

还,在您的Authed()处理程序中,您需要检查是否立即查看授权检查:真实成功;有关详细信息,请参阅此处的参考文档:

https://developers.google.com/api-客户端 - 库/ JavaScript / Reference / ReferenceCs#Gapiauthauthorize

还请参阅此处的弹出屏蔽的部分:

https://developers.google.com/api-客户端库/ JavaScript /功能/身份验证#POPUP

当“立即”授权失败时,将使用null令牌对象调用Authed回调,或包含“错误”字段的令牌对象;在这些情况下,您需要呈现用户可以单击的用户界面元素将重新运行Gapi.auth.Authorize调用,但是“立即”设置为false(或省略)。这允许打开授权弹出窗口,而不运行浏览器的弹出窗口阻止器的原因。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top