2017-07-20 300 views
1

我正在嘗試學習如何使用Google Signin登錄我的網站。我遵循我在本頁上找到的指南:https://developers.google.com/identity/sign-in/web/無法使用谷歌登錄登出

因此,我創建了一個新文檔,並複製他們在上述頁面上提供的代碼。我在標籤中添加了我的客戶端ID,並測試了代碼。 一切運作良好,我可以登錄。此外,在我看着我的控制檯,我可以看到來自console.log()的數據,如ID,電子郵件,姓名......

我繼續閱讀指南,我發現如何將這個頁面上添加一個退出按鈕:https://developers.google.com/identity/sign-in/web/sign-in 我實現了這個代碼,以下是完整的代碼,我有(無客戶端ID)

<html lang="en"> 
    <head> 
    <meta name="google-signin-scope" content="profile email"> 
    <meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com"> 
    <script src="https://apis.google.com/js/platform.js" async defer></script> 
    </head> 
    <body> 
    <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div> 
    <a href="#" onclick="signOut();">Sign out</a> 
    <script> 
     function onSignIn(googleUser) { 
     // Useful data for your client-side scripts: 
     var profile = googleUser.getBasicProfile(); 
     console.log("ID: " + profile.getId()); // Don't send this directly to your server! 
     console.log('Full Name: ' + profile.getName()); 
     console.log('Given Name: ' + profile.getGivenName()); 
     console.log('Family Name: ' + profile.getFamilyName()); 
     console.log("Image URL: " + profile.getImageUrl()); 
     console.log("Email: " + profile.getEmail()); 

     // The ID token you need to pass to your backend: 
     var id_token = googleUser.getAuthResponse().id_token; 
     console.log("ID Token: " + id_token); 
     }; 
    </script> 
<script> 
    function signOut() { 
    var auth2 = gapi.auth2.getAuthInstance(); 
    auth2.signOut().then(function() { 
     console.log('User signed out.'); 
    }); 
    } 
</script> 
    </body> 
</html> 

當我點擊它,我收到了'用戶退出'。在我的控制檯。但是,如果我刷新頁面,Google按鈕仍然表示我已登錄,並且配置文件信息會返回到我的控制檯中 - 即使我手動清除控制檯。 Sign out按鈕顯然不起作用,我不知道爲什麼。

任何人都有這方面的經驗?

感謝您的幫助!

回答

0

要撥打signOut,您需要撥打電話authorize()以獲取用於將用戶標記爲退出的id_token。

請參閱google-api-javascript-client GitHub上的this issue

一個代碼示例發佈在那裏,解釋說您需要先撥打gapi.auth.authorize,然後使用調用gapi.auth.signOut()的回調函數。

從本質上說,是這樣的:

gapi.auth.authorize(
    { 
     'client_id': CLIENT_ID, 
     'scope': SCOPES, 
     'immediate': false, 
     cookie_policy: 'single_host_origin', 
     response_type: 'token id_token' 
    }, 
    function (authResult) { gapi.auth.signOut();} 
);