This learning is more around adding OAuth for streamlit App. This video and code shared was a good reference to customize.
Creating a custom GCP project, providing OAuth Consent, Adding user info, onboarding is the process.
Step 1 - Fill Consent Screen and Add Test Users
Step 2 - Create Credentials
Sample code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#httpx_oauth==0.5.0 | |
#mysql-connector-python==8.0.28 | |
#pandas==1.3.4 | |
#python-dotenv==0.20.0 | |
#streamlit==1.8.0 | |
import streamlit as st | |
# IMPORTING LIBRARIES | |
import os | |
from numpy import void | |
import streamlit as st | |
import asyncio | |
from httpx_oauth.clients.google import GoogleOAuth2 | |
#from dotenv import load_dotenv | |
#load_dotenv('.env') | |
CLIENT_ID = "AAAAAAA" | |
CLIENT_SECRET = "BBBBBBBB" | |
REDIRECT_URI = "http://localhost:8501" | |
async def get_authorization_url(client: GoogleOAuth2, redirect_uri: str): | |
authorization_url = await client.get_authorization_url(redirect_uri, scope=["profile", "email"]) | |
return authorization_url | |
async def get_access_token(client: GoogleOAuth2, redirect_uri: str, code: str): | |
token = await client.get_access_token(code, redirect_uri) | |
return token | |
async def get_email(client: GoogleOAuth2, token: str): | |
user_id, user_email = await client.get_id_email(token) | |
return user_id, user_email | |
def get_login_str(): | |
client: GoogleOAuth2 = GoogleOAuth2(CLIENT_ID, CLIENT_SECRET) | |
authorization_url = asyncio.run( | |
get_authorization_url(client, REDIRECT_URI)) | |
return f'<a target="_self" href ="{authorization_url}" >Google login</a>' | |
def display_user() -> void: | |
client: GoogleOAuth2 = GoogleOAuth2(CLIENT_ID, CLIENT_SECRET) | |
# get the code from the url | |
code = st.experimental_get_query_params()['code'] | |
token = asyncio.run(get_access_token( | |
client, REDIRECT_URI, code)) | |
user_id, user_email = asyncio.run( | |
get_email(client, token['access_token'])) | |
st.write( | |
f"You're logged in as {user_email} and id is {user_id}") | |
if __name__ == '__main__': | |
st.title("Streamlit Oauth Login") | |
st.write(get_login_str(), unsafe_allow_html=True) | |
if st.button("display user"): | |
display_user() |
Keep Exploring!!!
No comments:
Post a Comment