I want to implement the login with google inside my streamlit app. The user should see directly the screen to select their google account even before being able to see the main screen app. Here is an example of implementation you can use. import asyncio from typing import Optional import jwt import streamlit as st from httpx_oauth.clients.google import GoogleOAuth2 import os client_id = os.environ['CLIENT_ID'] client_secret = os.environ['CLIENT_SECRET'] redirect_url = os.environ['REDIRECT_URL'] client = GoogleOAuth2(client_id=client_id, client_secret=client_secret) def decode_user(token: str): decoded_data = jwt.decode(jwt=token, options={"verify_signature": False}) return decoded_data async def get_authorization_url(client: GoogleOAuth2, redirect_url: str) -> str: authorization_url = await client.get_authorization_url( redirect_url, scope=["email"], extras_params={"access_type": "offline"}, ) return authorization_url def show_login_button(text: Optional[str] = "Login with Google", sidebar: bool = True): button_location = st.sidebar if sidebar else st authorization_url = asyncio.run(get_authorization_url(client=client, redirect_url=redirect_url)) if button_location.button(text, key="google_login", type="primary"): st.markdown(f'<meta http-equiv="refresh" content="0;url={authorization_url}">', unsafe_allow_html=True) async def get_access_token(client: GoogleOAuth2, redirect_url: str, code: str): token = await client.get_access_token(code, redirect_url) return token def get_access_token_from_query_params(client: GoogleOAuth2, redirect_url: str): if 'code' in st.query_params: code = st.query_params['code'] token = asyncio.run(get_access_token(client=client, redirect_url=redirect_url, code=code)) # Clear the query parameters st.query_params.clear() return token return None def get_logged_in_user_email() -> Optional[str]: if "email" in st.session_state: return st.session_state.email token = get_access_token_from_query_params(client, redirect_url) if token: user_info = decode_user(token=token["id_token"]) st.session_state["email"] = user_info["email"] return user_info["email"] return None
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter