of exercise within the AI world over the previous couple of weeks, a latest essential announcement by Streamlit that it now helps OpenID Join (OIDC) login authentication virtually handed me by.
Consumer authorisation and verification generally is a essential consideration for information scientists, machine studying engineers, and others concerned in creating dashboards, machine studying proofs of idea (PoCs), and different purposes. Protecting probably delicate information personal is paramount, so that you need to be sure that solely authorised customers can entry your app.
On this article, we’ll focus on this new characteristic of Streamlit and develop a easy app to showcase it. Our app is likely to be easy, however it demonstrates all the important thing issues you have to know when creating extra complicated software program.
What’s Streamlit?
In the event you’ve by no means heard of Streamlit, it’s an open-source Python library designed to construct and deploy interactive net purposes with minimal code rapidly. It’s broadly used for information visualisation, machine studying mannequin deployment, dashboards, and inner instruments. With Streamlit, builders can create net apps utilizing Python with out frontend expertise in HTML, CSS, or JavaScript.
Its key options embrace widgets for person enter, built-in caching for efficiency optimisation, and simple integration with information science libraries like Pandas, Matplotlib, and TensorFlow. Streamlit is especially standard amongst information scientists and AI/ML practitioners for sharing insights and fashions in a web-based interface.
In the event you’d wish to study extra about Streamlit, I’ve written a TDS article on utilizing it to create a knowledge dashboard, which you’ll be able to entry utilizing this link.
What’s OIDC?
OpenID Join (OIDC) is an authentication protocol that builds upon OAuth 2.0. It permits customers to securely register to purposes utilizing their current credentials from id suppliers like Google, Microsoft, Okta, and Auth0.
It permits single sign-on (SSO) and supplies person id info by way of ID tokens, together with e mail addresses and profile particulars. In contrast to OAuth, which focuses on authorisation, OIDC is designed explicitly for authentication, making it an ordinary for safe, scalable, and user-friendly login experiences throughout net and cellular purposes.
On this article, I’ll present you find out how to set issues up and write code for a Streamlit app that makes use of OIDC to immediate to your Google e mail and password. You should use these particulars to log in to the app and entry a second display screen that comprises an instance of a knowledge dashboard.
Stipulations
As this text focuses on utilizing Google as an id supplier, in the event you don’t have already got one, you’ll want a Google e mail tackle and a Google Cloud account. After getting your e mail, register to Google Cloud with it utilizing the hyperlink under.
https://console.cloud.google.com
In the event you’re fearful concerning the expense of signing up for Google Cloud, don’t be. They provide a free 90-day trial and $300 value of credit. You solely pay for what you utilize, and you may cancel your Cloud account subscription at any time, earlier than or after your free trial expires. Regardless, what we’ll be doing right here ought to incur no value. Nonetheless, I all the time suggest organising billing alerts for any cloud supplier you join — simply in case.
We’ll return to what you need to do to arrange your cloud account later.
Establishing our dev atmosphere
I’m growing utilizing WSL2 Ubuntu Linux on Home windows, however the next also needs to work on common Home windows. Earlier than beginning a challenge like this, I all the time create a separate Python growth atmosphere the place I can set up any software program wanted and experiment with coding. Now, something I do on this atmosphere can be siloed and gained’t influence my different initiatives.
I exploit Miniconda for this, however you should use any methodology that fits you greatest. If you wish to observe the Miniconda route and don’t have already got it, you need to first set up Miniconda.
Now, you possibly can arrange your atmosphere like this.
(base) $ conda create -n streamlit python=3.12 -y
(base) $ conda activate streamlit
# Set up required Libraries
(streamlit) $ pip set up streamlit streamlit-extras Authlib
(streamlit) $ pip set up pandas matplotlib numpy
What we’ll construct
This can be a streamlit app. Initially, there can be a display screen which shows the next textual content,
An instance Streamlit app exhibiting the usage of OIDC and Google e mail for login authentication
Please use the button on the sidebar to log in.
On the left sidebar, there will be two buttons. One says Login, and the other says Dashboard.
If a user is not logged in, the Dashboard button will be greyed out and unavailable for use. When the user presses the Login button, a screen will be displayed asking the user to log in via Google. Once logged in, two things happen:-
- The Login button on the sidebar changes to Logout.
- The Dashboard button becomes available to use. This will display some dummy data and graphs for now.
If a logged-in user clicks the Logout button, the app resets itself to its initial state.
NB. I have deployed a working version of my app to the Streamlit community cloud. For a sneak preview, click the link below. You may need to “wake up” the app first if no one has clicked on it for a while, but this only takes a few seconds.
Arrange on Google Cloud
To allow e mail verification utilizing your Google Gmail account, there are some things it’s a must to do first on the Google Cloud. They’re fairly simple, so take your time and observe every step rigorously. I’m assuming you’ve already arrange or have a Google e mail and cloud account, and that you just’ll be creating a brand new challenge to your work.
Go to Google Cloud Console and log in. It is best to see a display screen much like the one proven under.
You want to arrange a challenge first. Click on the Challenge Picker button. It’s instantly to the proper of the Google Cloud emblem, close to the highest left of the display screen and can be labelled with the identify of considered one of your current initiatives or “Choose a challenge” in the event you don’t have an current challenge. Within the pop-up that seems, click on the New Challenge button situated on the prime proper. It will allow you to insert a challenge identify. Subsequent, click on on the Create button.
As soon as that’s accomplished, your new challenge identify can be displayed subsequent to the Google Cloud emblem on the prime of the display screen. Subsequent, click on on the hamburger-style menu on the prime left of the web page.
- Navigate to APIs & Providers → Credentials
- Click on Create Credentials → OAuth Consumer ID
- Choose Internet software
- Add http://localhost:8501/oauth2callback as an Licensed Redirect URI
- Pay attention to the Consumer ID and Consumer Secret as we’ll want them in a bit.
Native setup and Python code
Resolve which native folder your principal Python Streamlit app file will dwell in. In there, create a file, resembling app.py, and insert the next Python code into it.
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# ——— Web page setup & state ———
st.set_page_config(page_title="SecureApp", page_icon="🔑", format="large")
if "web page" not in st.session_state:
st.session_state.web page = "principal"
# ——— Auth Helpers ———
def _user_obj():
return getattr(st, "person", None)
def user_is_logged_in() -> bool:
u = _user_obj()
return bool(getattr(u, "is_logged_in", False)) if u else False
def user_name() -> str:
u = _user_obj()
return getattr(u, "identify", "Visitor") if u else "Visitor"
# ——— Important & Dashboard Pages ———
def principal():
if not user_is_logged_in():
st.title("An instance Streamlit app exhibiting the usage of OIDC and Google e mail for login authentication")
st.subheader("Use the sidebar button to log in.")
else:
st.title("Congratulations")
st.subheader("You’re logged in! Click on Dashboard on the sidebar.")
def dashboard():
st.title("Dashboard")
st.subheader(f"Welcome, {user_name()}!")
df = pd.DataFrame({
"Month": ["Jan","Feb","Mar","Apr","May","Jun"],
"Gross sales": np.random.randint(100,500,6),
"Revenue": np.random.randint(20,100,6)
})
st.dataframe(df)
fig, ax = plt.subplots()
ax.plot(df["Month"], df["Sales"], marker="o", label="Gross sales")
ax.set(xlabel="Month", ylabel="Gross sales", title="Month-to-month Gross sales Development")
ax.legend()
st.pyplot(fig)
fig, ax = plt.subplots()
ax.bar(df["Month"], df["Profit"], label="Revenue")
ax.set(xlabel="Month", ylabel="Revenue", title="Month-to-month Revenue")
ax.legend()
st.pyplot(fig)
# ——— Sidebar & Navigation ———
st.sidebar.header("Navigation")
if user_is_logged_in():
if st.sidebar.button("Logout"):
st.logout()
st.session_state.web page = "principal"
st.rerun()
else:
if st.sidebar.button("Login"):
st.login("google") # or "okta"
st.rerun()
if st.sidebar.button("Dashboard", disabled=not user_is_logged_in()):
st.session_state.web page = "dashboard"
st.rerun()
# ——— Web page Dispatch ———
if st.session_state.web page == "principal":
principal()
else:
dashboard()
This script builds a two-page Streamlit app with Google (or OIDC) login and a easy dashboard:
- Web page setup & state
- Configures the browser tab (title/icon/format).
- Makes use of
st.session_state["page"]to recollect whether or not you’re on the “principal” display screen or the “dashboard.”
- Auth helpers
_user_obj()safely seize thest.personobject if it exists.user_is_logged_in()anduser_name(). Test whether or not you’ve logged in and get your identify (or default to “Visitor”).
- Important vs. Dashboard pages
- Important: In the event you’re not logged in, show a title/subheader prompting you to log in; in the event you’re logged in, show a congratulatory message and direct you to the dashboard.
- Dashboard: greets you by identify, generates a dummy DataFrame of month-to-month gross sales/revenue, shows it, and renders a line chart for Gross sales plus a bar chart for Revenue.
- Sidebar navigation
- Reveals a Login or Logout button relying in your standing (calling
st.login("google")orst.logout()). - Reveals a “Dashboard” button that’s solely enabled when you’re logged in.
- Reveals a Login or Logout button relying in your standing (calling
- Web page dispatch
- On the backside, it checks
st.session_state.web pageand runs bothprincipal()ordashboard()accordingly.
- On the backside, it checks
Configuring Your secrets and techniques.toml for Google OAuth Authentication
In the identical folder the place your app.py file lives, create a subfolder referred to as .streamlit. Now go into this new subfolder and create a file referred to as secrets and techniques.toml. The Consumer ID and Consumer Secret from Google Cloud needs to be added to that file, together with a redirect URI and cookie secret. Your file ought to look one thing like this,
#
# secrets and techniques.toml
#
[auth]
redirect_uri = "http://localhost:8501/oauth2callback"
cookie_secret = "your-secure-random-string-anything-you-like"
[auth.google]
client_id = "************************************.apps.googleusercontent.com"
client_secret = "*************************************"
server_metadata_url = "https://accounts.google.com/.well-known/openid-configuration"
Okay, we should always now be capable of run our app. To do this, return to the folder the place app.py lives and sort this into the command line.
(streamlit) $ streamlit run app.py
If all has gone nicely along with your code and set-up, it is best to see the next display screen.

Discover that the Dashboard button on the sidebar needs to be greyed out since you’re not logged in but. Begin by clicking the Login button on the sidebar. It is best to see the display screen under (I’ve obscured my credentials for safety causes),

When you select an account and log in, the Streamlit app show will change to this.

Additionally, you will discover that the Dashboard button is now clickable, and once you click on it, it is best to see a display screen like this.

Lastly, log again out, and the app ought to return to its preliminary state.
Abstract
On this article, I defined that correct OIDC authorisation is now obtainable to Streamlit customers. This lets you be sure that anybody utilizing your app is a legit person. Along with Google, it’s also possible to use standard suppliers resembling Microsoft, OAuth, Okta, and others.
I defined what Streamlit was and its makes use of, and briefly described the OpenID Join (OIDC) authentication protocol.
For my coding instance, I centered on utilizing Google because the authenticator and confirmed you the prerequisite steps to set it up appropriately to be used on Google’s Cloud platform.
I additionally supplied a pattern Streamlit app that reveals Google authorisation in motion. Though this can be a easy app, it highlights all methods you require ought to your wants develop in complexity.

