使用Oauth 2 Google

时间:2017-03-27 20:57:07

标签: javascript angular oauth google-oauth google-authentication

我正在尝试使用Google API对用户进行身份验证。我必须进行身份验证,但我不知道如何在登录后重定向用户以及如何注销。

我尝试使用Google文档:https://developers.google.com/identity/sign-in/web/sign-in。但我收到了一个错误:+---------+----------------------------+--------------------+-----------------+-----------------+--------------+-----------+-----------+ | cluster | count_total_characteristic | count_both_1_and_2 | count_only_in_1 | count_only_in_2 | both_1_and_2 | only_in_1 | only_in_2 | +---------+----------------------------+--------------------+-----------------+-----------------+--------------+-----------+-----------+ | A | 3 | 2 | 1 | 0 | [1,2] | [3] | [] | | B | 3 | 2 | 0 | 1 | [2,3] | [] | [4] | +---------+----------------------------+--------------------+-----------------+-----------------+--------------+-----------+-----------+

以下是代码:

Cannot read property 'getAuthInstance' of undefined

有谁知道如何修复它?

1 个答案:

答案 0 :(得分:0)

您需要在脚本中使用gapi.auth2.init()方法,或在<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">中使用<head>

您的代码如下所示:

<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>
<script>
    var redirectUri = 'http://localhost:4200/list';
    function onSignIn(googleUser) {
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
    }
    function signOut() {
        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () {
            console.log('User signed out.');
        });
    }
</script>

有关gapi.auth2.init()方法的更多信息:https://developers.google.com/identity/sign-in/web/reference#gapiauth2initwzxhzdk19paramswzxhzdk20