如何正确使用Google'的Javascript OAuth2.0库

How to correctly use Google's Javascript OAuth2.0 library

本文关键字:Javascript OAuth2 何正确 Google      更新时间:2023-09-26

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

'[{"error":{"code":401,"message":"Login Required","data":[{"domain":"global","reason":"Required","message":"Login Required","locationType":"header","location":"Authorization"}]},"id":"gapRpc"}]'

第二次点击结果是

[{"id":"gapRpc","result":{"id:"1115793426680xxxx","电子邮件":"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>-->

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

由于在对gap.auth.authorize的调用中"authed"后面有括号,authed()回调将在调用gap.auth·阿uthorize之前立即运行。

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

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

另请参阅此处关于弹出式阻止的部分:

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

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