Using Oauth2 to sign-in users with Google using Google Java Script Library

Example project here:  Sign-in with Google using Google Java Script library

 

  • Main project
<head>
  <style>
    #signIn {
      width: 80%;
      height: 50%;
      display: none;
    }

    span {
      border: 1px solid silver;
      padding: 10px;
      cursor: pointer;
      font-size: 10px;
    }
  </style>
  <script>
    function userLoggedIn(userObject) {
      document.getElementById('signIn').style.display = 'none';
      document.getElementById('head').innerHTML = `Wellcome ${userObject.given_name} ${userObject.family_name} ! <hr/>email: ${userObject.email} `;
    }

    function showLogInPopup() {
      document.getElementById('signIn').style.display = 'block';
    }
  </script>  
</head>

<body>
  <h1 id="head">Integrating Google Sign-in for Websites with Google library. <span onclick="showLogInPopup()">Log In</span></h1>

  <iframe id="signIn" src="google-sign-in.html"></iframe>
</body>
  • create iFrame with the log in button
<head>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
    <script>
        function userLoggedIn(credential) {
            document.getElementById('log-in-iframe').style.display = 'none';
            alert(credential);
        }
    </script>
</head>

<body>
    Log in with Google
    <div id="log-in-button">
        <div id="g_id_onload"
            data-client_id="989056576533-mtef8cl5is5ogjh3np580ireurns7l5k.apps.googleusercontent.com"
            data-context="signin"
            data-response-type="code"
            data-ux_mode="popup"
            data-login_uri="https://www.toni-develops.com/external-files/examples/oauth-with-google-with-popup/callback.php"
            data-itp_support="true"
            data-auto_prompt="false">
        </div>

        <div class="g_id_signin"
            data-type="standard"
            data-shape="rectangular"
            data-theme="filled_blue"
            data-text="signin_with"
            data-size="large"
            data-logo_alignment="left">
        </div>   
    </div>
</body>
  • create callback
<html>
<head>
</head>

<body>
  <pre>
  <?php
    $token = $_POST['credential'];
    $userObject = json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $token)[1]))));
    print_r($userObject);
  ?>  
  </pre>
  <script>
  var userObject = {
    given_name : "<?php echo $userObject->given_name ?>",
    family_name : "<?php echo $userObject->family_name ?>",
    email : "<?php echo $userObject->email ?>"
  }

  function passUserObjectToParentDocument(userObject) {
    parent.userLoggedIn(userObject);
  }
  </script>
  <button onclick="passUserObjectToParentDocument(userObject)">continue</button>
</body>
</html>

 

Example project here:  Sign-in with Google using Google Java Script library

Leave a Reply