Google Authentication in a streamlit app

  1. Create a new project on the Google Cloud Console:
  2. Enable the Google Sign-In API:
    • In the Google Cloud Console, navigate to the “APIs & Services” > “Library” section.
    • Search for “Google Sign-In API” and enable it for your project.
  3. Configure the OAuth consent screen:
    • In the Google Cloud Console, navigate to the “APIs & Services” > “OAuth consent screen” section.
    • Choose an “External” user type and click “Create”.
    • Provide a name for your application, enter the authorized domain (e.g., localhost for local development), and add any additional required information.
    • Save the changes.
  4. Create OAuth credentials:
    • In the Google Cloud Console, navigate to the “APIs & Services” > “Credentials” section.
    • Click “Create Credentials” and select “OAuth client ID”.
    • Choose “Web application” as the application type.
    • Enter a name for the OAuth client ID.
    • Add the authorized JavaScript origins (e.g., http://localhost:8501 for Streamlit’s default development server).
    • Add the authorized redirect URI (e.g., http://localhost:8501/).
    • Click “Create” to generate the OAuth client ID and client secret.
  5. Install the required Python libraries:
    • Open a terminal or command prompt and install the google-auth library using pip:
     pip install google-auth
  1. Implement the Google Authentication in your Streamlit app:
    • Import the necessary libraries in your Python script:
     import streamlit as st
     from google.oauth2 import id_token
     from google.auth.transport import requests
  1. Add the authentication logic in your Streamlit app:
def main():
    st.title("Your Streamlit App")
    
    # Google Authentication
    st.subheader("Google Authentication")
    client_id = "YOUR_CLIENT_ID"  # Replace with your OAuth client ID
    token = st.text_input("Enter your Google ID token", type="password")
    if st.button("Authenticate"):
        try:
            idinfo = id_token.verify_oauth2_token(token, requests.Request(), client_id)
            if idinfo['aud'] != client_id:
                raise ValueError("Invalid client ID")
            st.success(f"Authentication successful: {idinfo['name']}")
            # Continue with the rest of your app logic here
        except ValueError as e:
            st.error("Authentication failed")
            st.error(e)
    
    # Other app content
    # ...
    
if __name__ == "__main__":
    main()
  • Replace "YOUR_CLIENT_ID" with your OAuth client ID obtained from the Google Cloud Console.
  1. Run your Streamlit app:
    • Open a terminal or command prompt and navigate to the directory where your Python script is located.
    • Run your Streamlit app using the following command:
streamlit run your_script.py
8 Likes