質問

OAuth2を使用して、JavaScriptクライアントからGoogle APIにアクセスしようとしています。私はユーザーに要求を認証することに成功しましたが、以下のコードを実行するときに予期しない動作があります。初めて 'authorize'ボタンをクリックすると、結果は次のとおりです。

'[{"error":{"コード":401、 "message": "login必須"、 "data":[{"domain": "reason": "必須"、 "メッセージmsgstr "" "Login Required"、 "LocationType": "Header"、 "Location": "承認"}]}、 "id": "GAPIRPC"}] '

2回目のクリック結果は

[{"id": "gapirpc"、 "gapirpc":{"id": "email": "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>-->
.

コードの最初の実行と2回目の実行での認証が成功したことに「ログインが必要」となるのかを説明してください。

役に立ちましたか?

解決

GAPI.AUTH.AUTHORIZEの呼び出しで「認証された」直後の括弧のために、authed()コールバックはgapi.auth.authorizeの呼び出しの前にすぐに実行されます。

また、あなたの認証された()ハンドラでは、即時に承認をチェックするかどうかを確認する必要があります。詳細については、参照文書を参照してください。

https://developers.google.com/api-クライアントライブラリ/ JavaScript / reference / referenceedocs #papiauthauthorize

は、ここでのポップアップブロックの節も参照します。

https://developers.google.com/api-クライアントライブラリ/ JavaScript /機能/認証#ポップアップ

「即時」承認が失敗すると、認証されたコールバックは、NULLトークンオブジェクト、または「エラー」フィールドを含むトークンオブジェクトで呼び出されます。このような場合、ユーザーがクリックすることができるユーザーインターフェイス要素を提示する必要があります.auth.authorize呼び出しが「即値」に設定されている(または省略)。これにより、ブラウザのポップアップブロッカーが稼働せずに認証ポップアップを開くことができます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top