Upgrade to Pro

How to Implement Google Auto-login on a Website

To implement Google auto-login on a website, you need to use Google's OAuth 2.0 authentication system. Google offers a service called Google Sign-In which simplifies this process and allows users to log in using their Google account.

Here’s a step-by-step guide to implement Google auto-login (Google Sign-In) in a website:

1. Set Up Your Google Developer Console Project

  1. Create a Project:

  2. Enable Google Sign-In API:

    • In the project dashboard, search for "Google Sign-In" and enable the API.
  3. Configure OAuth Consent Screen:

    • Go to the "OAuth consent screen" tab in the Google Developer Console.
    • Fill out the required information (app name, support email, etc.).
    • Under "Scopes," select the permissions your app needs (e.g., access to the user's basic profile, email, etc.).
  4. Create OAuth 2.0 Credentials:

    • In the "Credentials" tab, create new credentials by selecting OAuth 2.0 Client IDs.

    • Choose Web application as the application type.

    • Add your website’s authorized JavaScript origins and redirect URIs. For example:

      • Authorized JavaScript origins: https://yourwebsite.com
      • Authorized redirect URIs: https://yourwebsite.com/oauth2callback
    • After creation, you’ll get a Client ID and Client Secret.

2. Include the Google Sign-In JavaScript Library

To use Google Sign-In, you need to add the Google API JavaScript client to your HTML.

<script src="https://apis.google.com/js/platform.js" async defer></script>

3. Add the Google Sign-In Button

You can use a pre-made Google Sign-In button or create a custom one. Here’s the code for a standard button:

<div class="g-signin2" data-onsuccess="onSignIn"></div>

This will display a Google Sign-In button on your page. The data-onsuccess="onSignIn" attribute will call the onSignIn function when the user successfully logs in.

4. Handle the Sign-In Success

Create a JavaScript function that handles the sign-in callback and processes the user's information.

<script type="text/javascript">
  function onSignIn(googleUser) {
    // Get the Google user profile
    var profile = googleUser.getBasicProfile();
    var email = profile.getEmail();  // Get the user's email
    var id_token = googleUser.getAuthResponse().id_token;  // ID Token for backend verification
    
    // Send the ID token to your backend for verification and auto-login logic
    // For example, send the token to a server endpoint using AJAX or fetch
    fetch('/verify-google-token', {
      method: 'POST',
      body: JSON.stringify({ token: id_token }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        // Handle auto-login success (redirect, welcome message, etc.)
      } else {
        // Handle error or unsuccessful auto-login
      }
    })
    .catch(error => console.error('Error:', error));
  }
</script>

5. Verify the Token on the Backend

Once you receive the ID token in the JavaScript function, you need to verify it on your backend server. You can use Google’s libraries to verify the token and ensure it is valid.

Here’s an example in Python (using Flask):

from google.oauth2 import id_token
from google.auth.transport.requests import Request
import requests

def verify_google_token(id_token_str):
    try:
        # Specify your CLIENT_ID (from the Developer Console)
        CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com'
        
        # Verify the token
        id_info = id_token.verify_oauth2_token(id_token_str, Request(), CLIENT_ID)
        
        if id_info['iss'] != 'accounts.google.com' and id_info['iss'] != 'https://accounts.google.com':
            raise ValueError('Wrong issuer.')
        
        # Proceed with user info (id_info contains user details)
        user_id = id_info['sub']
        email = id_info['email']
        return {'user_id': user_id, 'email': email, 'success': True}
    except ValueError as e:
        # Invalid token
        return {'success': False, 'message': str(e)}

6. Auto-login the User

If the token is successfully verified, you can log the user into your website by creating a session or a JWT (JSON Web Token) for the user.

You may also need to associate the Google account with your website’s database, ensuring the user’s Google email is tied to their profile.


Key Considerations:

  • Security: Never trust the data directly from the frontend. Always verify the token in the backend.
  • Session Management: Once verified, you can create a session for the user or issue a JWT to maintain the login state.
  • Logout: Google Sign-In provides a signOut function to log the user out when necessary.
<button onclick="signOut()">Sign out</button>

<script>
  function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
  }
</script>

With this, you'll have Google auto-login integrated into your website. Let me know if you'd like more details on a specific part!

Would you like a backend implementation with token validation as well?

Flowise Tech https://flowisetech.com