Implementing Google Login in Android with React Native and Expo and Validating with a Python Server

Tiempo de lectura: 4 minutos

This is how we can implement Google Sign in using React Native and Expo in a simple way.

Houses yellow - Pexels

The first thing we will do is use this library @react-native-google-signin/google-signin

The installation is:

npx expo install @react-native-google-signin/google-signin

We will configure it once installed.

First we will create our handler in Typescript:

html

import React from "react"; import { View, Button, Text, StyleSheet } from "react-native"; import { GoogleSignin, SignInResponse, statusCodes, } from "@react-native-google-signin/google-signin";// Initial setup of GoogleGoogleSignin.configure({  webClientId: "YOUR_WEB_CLIENT_ID.apps.googleusercontent.com",   // Add your iOS client ID (optional for iOS)  iosClientId: "YOUR_IOS_CLIENT_ID.apps.googleusercontent.com",});// Function to close the sessionexport async function closeGoogleSession() {  try {     const currentUser = await GoogleSignin.getCurrentUser();     if (currentUser) {       await GoogleSignin.signOut();       console.log("Session closed successfully");     } else {       console.log("No active session");     }  } catch (error) {     console.error("Error closing the session:", error);   }}// Login component with Googleconst GoogleAuthentication: React.FC = () => {  const handleGoogleLogin = async () => {    try {      await GoogleSignin.hasPlayServices();       const userInfo: SignInResponse = await GoogleSignin.signIn();       const data = userInfo.data;       const idToken = data?.idToken;       const user = data?.user;      console.log("User information:", userInfo);      if (idToken) {        console.log("idToken:", idToken);         // TODO: Send the idToken to your server for validation        // For example with axios:        // await axios.post("https://miapi.com/loginGoogle", { token: idToken });        // TODO: Store session data in AsyncStorage or Context      }    } catch (error: any) {      console.log("Error logging in with Google:", error);      switch (error.code) {        case statusCodes.SIGN_IN_CANCELLED:          console.log("User cancelled the login");        break;        case statusCodes.IN_PROGRESS:          console.log("Login in progress");        break;        case statusCodes.PLAY_SERVICES_NOT_AVAILABLE:          console.log("Google Play Services not available");        break;        default:          console.log("Other error:", error);      }    };  };  return (          Login with Google (Generic Example)      

And now we’ll create the code to allow us to log in.

webClientId: «YOUR_WEB_CLIENT_ID.apps.googleusercontent.com», // TODO: add your client ID of Google

for this, we have to go to the Firebase console

We need to enable Google authentication by clicking on the “Method of access” button.

We chose Google and enabled:

Enable Google sign in Firebase

Now we will add the SHA key of our certificates.

To do this, we use the following command:

keytool -list -v -keystore android/app/debug.keystore -alias androiddebugkey -storepass android -keypass android

With this command, we get the SHA key of the signature key for the development environment.

If we want the production version, we can apply the same command with the production key and alias and correct password or download it from expo.

Once we have the SHA key, we copy it to the corresponding section: project configuration > general > your apps

Your apps Firebase

We need to generate our client code once we have the keys attached. To do this, we simply go back to Google Sign and open the SDK Web Configuration

We copy this code and it is the one we need to use in our client code:

html

webClientId: "TU_WEB_CLIENT_ID.apps.googleusercontent.com",

<

p Once added, we will validate the call.

<

p To do this, we need to send the token obtained once login with Google to a server in this case Python.

 console.log("User information:", userInfo); if (idToken) { console.log("idToken:", idToken); // TODO: here you can send the idToken to your server for validation // For example with axios: // await axios.post("https://myapi.com/loginGoogle", { token: idToken});

The validation code will be:

def validate_google_token(token_id):    CLIENTS_IDs = ["", ""] # print(f"The token for validation is: {token_id}")    try:        id_info = id_token.verify_oauth2_token(token_id, requests.Request()) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request())        # print(f"Token information is: {id_info}")        # Check that the client ID is correct        if id_info["azp"] not in CLIENTS_IDs:            raise ValueError("The client is not valid.")        userid = id_info["sub"]        # print(f"The user is: {userid}")        # If we reach this point, the token is valid        return id_info    except ValueError as e:        # Token is not valid        print(f"Validation error: {e}")        return -1

We need to add the following variable:

CLIENTS_IDs = ["", ""]

To do this, we need to decode the token obtained (idToken) from this website: https://www.jwt.io/

We also need to get the value of the azp field and add it to the array of possible variables. If we have more clients, we can add them.

This will check correctly the token.

Leave a Comment