基本的Google登录。将令牌发送到服务器

时间:2018-08-11 19:24:20

标签: php google-signin

我正在尝试建立一个通过Google登录对用户进行身份验证的系统。我在Google开发人员网站上使用的代码仅带有我认为需要的修改(替换了我的客户端ID和用来处理服务器上令牌的php页面的名称)。登录有效。现在,我正在尝试将令牌发送到我的服务器。我认为以下代码(以“ var xhr”开头)应该在服务器上打开页面 googletest.php ,并将POST变量 idtoken 传递给它。那没有发生。我成功登录,但是googletest.php无法加载。我哪里错了?我不明白如何在服务器上处理令牌吗?

这是主要的登录页面:

<html lang="en">
  <head>
    <meta name="google-signin-scope" content="profile email">
    <meta name="google-signin-client_id" content="[My 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>
    <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);
      };
      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'https://rsdacademy.net/googletest.php');
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.onload = function() {
        console.log('Signed in as: ' + xhr.responseText);
      };
      xhr.send('idtoken=' + id_token);
    </script>


    <!--<a href="#" onclick="signOut();">Sign out</a>
    <script>
    function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
    }
    </script>-->
  </body>
</html>

这是googletest.php:

<?
$token = $_POST["idtoken"];

print "$token";
?>

0 个答案:

没有答案