To add the "Sign in with Google" feature to your Streamlit app, you can use the OAuth 2.0 protocol with the help of the authlib
library. Here's a step-by-step guide:
Step 1: Set up a Google Cloud Project
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Navigate to the "APIs & Services" > "Credentials" section.
- Click on "Create Credentials" and choose "OAuth client ID".
- Configure the consent screen as required.
- Set the application type to "Web application".
- Add authorized redirect URIs. For a local Streamlit app, you can use
http://localhost:8501/oauth2callback
.
- Note down the Client ID and Client Secret.
Step 2: Install Required Libraries
Install authlib
if you haven't already:
Step 3: Modify Your App
Add the following imports and global variables to your app.py
:
from authlib.integrations.requests_client import OAuth2Session
import streamlit as st
# Google OAuth2 config
GOOGLE_CLIENT_ID = "your-client-id"
GOOGLE_CLIENT_SECRET = "your-client-secret"
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
Replace "your-client-id"
and "your-client-secret"
with the credentials you obtained from the Google Cloud Console.
Step 4: Implement the OAuth Flow
Add the following functions to handle the OAuth flow:
def get_google_oauth_session(redirect_uri="http://localhost:8501/oauth2callback"):
"""Create an OAuth session for Google."""
client = OAuth2Session(
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
scope=["openid", "email", "profile"],
redirect_uri=redirect_uri,
)
return client
def authenticate_user():
"""Authenticate the user with Google OAuth."""
oauth = get_google_oauth_session()
authorization_url, state = oauth.create_authorization_url(GOOGLE_DISCOVERY_URL)
st.session_state["oauth_state"] = state
return authorization_url
def get_user_info(code):
"""Get user information from the OAuth provider."""
oauth = get_google_oauth_session()
token = oauth.fetch_token(
GOOGLE_DISCOVERY_URL,
authorization_response=f"http://localhost:8501/oauth2callback?code={code}",
state=st.session_state["oauth_state"],
)
user_info = oauth.get("https://openidconnect.googleapis.com/v1/userinfo").json()
return user_info
Step 5: Update the Main App Logic
Modify the main()
function to include the Google sign-in option:
def main():
st.sidebar.title("ChatGPT-4 Query Manager")
mode = st.sidebar.selectbox("Mode", ["Login", "Sign Up", "Sign in with Google"])
if mode == "Sign in with Google":
if "code" not in st.experimental_get_query_params():
# Redirect to Google for authentication
auth_url = authenticate_user()
st.sidebar.markdown(f'[Sign in with Google]({auth_url})', unsafe_allow_html=True)
else:
# Handle the callback from Google
code = st.experimental_get_query_params()["code"][0]
user_info = get_user_info(code)
st.session_state["authenticated"] = True
st.session_state["user"] = user_info["email"]
st.experimental_set_query_params() # Clear the query params
st.sidebar.success("Logged in successfully!")
st.sidebar.write(f"Welcome, {user_info['email']}")
# Handle other modes (Login and Sign Up) and display booking calendar
# ...
Step 6: Run Your App
Start your Streamlit app and test the "Sign in with Google" feature.
Make sure to replace http://localhost:8501
with your actual app's URL if you're deploying it online. Also, update the authorized redirect URIs in the Google Cloud Console accordingly.