Implementing Google OAuth in Streamlit | by Duc Anh Bui | Towards Data Science

At HousingAnywhere, we often utilize Streamlit to build interactive dashboards for our metrics and targets. Streamlit is a relatively new tool. It has a lot of potential use cases and is very easy to use but can be lacking in some areas such as security. A popular, simple method for security most people use for Streamlit is to utilise SessionState, but it is very susceptible to attacks (e.g. brute forcing).
In this article, I’ll show you how to implement Google OAuth 2.0 to better secure your application.
First, let’s configure the OAuth consent screen.
Go to the Google API Console OAuth consent screen page.Choose Internal so only users within your organization can access the app.Fill in the necessary information.Click Add Scopes and add any necessary scopes you require. For this example, we don’t need any.
Go to the Google API Console OAuth consent screen page.
Choose Internal so only users within your organization can access the app.
Fill in the necessary information.
Click Add Scopes and add any necessary scopes you require. For this example, we don’t need any.
Next, we need to create an authorization credential from GCP:
Go to the Credentials page in GCP ConsoleClick on Create Credentials > OAuth client ID.Select Web Application for Application type and fill in the name for your client.Fill in redirect URIs for your application. These are the links you want the users to be redirected back to after logging in. For example, in local environment, you can use http://localhost:8501Note down the Client ID and Client Secret for later.
Go to the Credentials page in GCP Console
Click on Create Credentials > OAuth client ID.
Select Web Application for Application type and fill in the name for your client.
Fill in redirect URIs for your application. These are the links you want the users to be redirected back to after logging in. For example, in local environment, you can use http://localhost:8501
Note down the Client ID and Client Secret for later.
Install the following libraries
streamlit==0.81.1httpx-oauth==0.3.5
We’ll utilize SessionState to store the token returned from Google API. Store this in a session_state.py :
In the main application, we first define these three variables to store the Client ID and Secret from earlier:
client_id = os.environ['GOOGLE_CLIENT_ID']client_secret = os.environ['GOOGLE_CLIENT_SECRET']redirect_uri = os.environ['REDIRECT_URI']
We’ll be using httpx-oauth as our authorization client:
client = GoogleOAuth2(client_id, client_secret)
Now, create a function that handles creating the authorization URL:
async def write_authorization_url(client,                                  redirect_uri):    authorization_url = await client.get_authorization_url(        redirect_uri,        scope=["email"],        extras_params={"access_type": "offline"},    )    return authorization_urlauthorization_url = asyncio.run(    write_authorization_url(client=client,                            redirect_uri=redirect_uri))st.write(f'''<h1>    Please login using this <a target="_self"    href="{authorization_url}">url</a></h1>''',         unsafe_allow_html=True)
Once the user gets redirected back from Google Authorisation page, the authorization code is contained in the URL. We’ll obtain it using st.experimental_get_query_params()
code = st.experimental_get_query_params()['code']
And get the token from Google with this function:
async def write_access_token(client,                             redirect_uri,                             code):    token = await client.get_access_token(code, redirect_uri)    return tokentoken = asyncio.run(    write_access_token(client=client,                       redirect_uri=redirect_uri,                       code=code))session_state.token = token
The process can be visualized as follows:
We store the token using the SessionState utility so that the user does not need to re-authorize during a session. Since we’re storing the token per session, refreshing the page will trigger the authorization process again.
Securing your data is a crucial aspect of building data applications. With Google OAuth, you can sleep a little better at night knowing that your applications is better secured against a possible breach. You can check out the codes for the whole application here on GitHub.