Verify Google Auth Token (Google Sign) Using Python

Tiempo de lectura: 2 minutos

Today we’re going to learn how we can verify a token generated with Google Sign-In from a front-end client by sending it to the back-end.

In this case, we’ll be using Python.

Of course, here’s a step-by-step tutorial for validating a Google Sign-In token in Python using the google-auth library.

Step 1: Install the google-auth library

Make sure you have the google-auth library installed by running the following command in your terminal or console:

pip install google-auth

Step 2: Obtain the Google Client ID

Make sure you have set up an application in the Google Cloud Console. Get the client ID of your application; you’ll need it to validate the token.

Step 3: Create a validation script

Create a Python script with the following code:

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

def validar_token_google(token):
    CLIENT_ID = 'your_google_client_id'

    try:
        id_info = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)

        # If it reaches this point, the token is valid
        return id_info
    except ValueError as e:
        # The token is not valid
        print(f'Validation error: {e}')
        return None

# Using the function
google_token = 'your_google_token_to_validate'
result = validar_token_google(google_token)

if result:
    print(f'Valid token. User information: {result}')
else:
    print('Invalid token.')

Make sure to replace 'your_google_client_id' with the client ID of your application.

Here’s how you can get the Google client ID (https://devcodelight.com/?p=7297). You’ll need to follow those steps until you download the .json file; the Google client ID is within that file:

NOTE: Remember that the token to be validated is of type oauth and is obtained from a GoogleSignInAccount with the idToken attribute

Step 4: Run the script

Save the script with a descriptive name, for example, validate_google_token.py. Then, execute it from the terminal or console:

python validate_google_token.py

The script will indicate whether the token is valid or not and will display the user information if the token is valid.

This tutorial provides you with a foundation for validating Google Sign-In tokens in Python. You can integrate this code into your web or backend application according to your specific needs.

Leave a Comment