【问题标题】:How to correctly use Google's Javascript OAuth2.0 library如何正确使用谷歌的Javascript OAuth2.0库
【发布时间】:2013-11-19 02:28:53
【问题描述】:

我正在尝试使用 Oauth2 从我的 javascript 客户端访问一些谷歌 API。我已经成功地让用户对请求进行身份验证,但是在运行下面的代码时会出现一些我想了解的意外行为。当我第一次点击“授权”按钮时,结果是:

'[ { "error": { "code": 401, "message": "需要登录", "data": [ { "domain": "global", "reason": "required", "message ": "需要登录", "locationType": "header", "location": "Authorization" } ] }, "id": "gapiRpc" } ] '

第二次点击的结果是

[ { "id": "gapiRpc", "result": { "id": "1115793426680xxxx", "email": "xxxxx@gmail.com", "verified_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>-->

您能否解释一下为什么我会在第一次执行代码时获得“需要登录”而在第二次执行时获得成功的身份验证?

【问题讨论】:

    标签: javascript oauth-2.0 google-oauth


    【解决方案1】:

    由于在对 gapi.auth.authorize 的调用中紧跟在“authed”之后的括号,因此在调用 gapi.auth.authorize 之前立即运行 authed() 回调。

    此外,在您的 authed() 处理程序中,您需要检查是否使用 immediate: true 成功进行授权检查;有关更多详细信息,请参阅此处的参考文档:

    https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauthauthorize

    另请参阅此处的弹出窗口阻止部分:

    https://developers.google.com/api-client-library/javascript/features/authentication#popup

    当“立即”授权失败时,将使用 null 令牌对象或包含“错误”字段的令牌对象调用 authed 回调;在这些情况下,您需要提供用户可以单击的用户界面元素,该元素将重新运行 gapi.auth.authorize 调用,但“立即”设置为 false(或省略)。这允许在不与浏览器的弹出窗口阻止程序发生冲突的情况下打开授权弹出窗口。

    【讨论】:

      猜你喜欢
      • 2018-11-02
      • 2021-07-28
      • 2014-07-24
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      • 2014-10-16
      相关资源
      最近更新 更多