of exercise within the AI world over the previous few weeks, a latest necessary announcement by Streamlit that it now helps OpenID Join (OIDC) login authentication virtually handed me by.
Consumer authorisation and verification could be a essential consideration for information scientists, machine studying engineers, and others concerned in creating dashboards, machine studying proofs of idea (PoCs), and different functions. Conserving doubtlessly delicate information personal is paramount, so that you need to make 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, nevertheless it demonstrates all the important thing issues you might want to know when creating extra complicated software program.
What’s Streamlit?
Should you’ve by no means heard of Streamlit, it’s an open-source Python library designed to construct and deploy interactive net functions with minimal code rapidly. It’s broadly used for information visualisation, machine studying mannequin deployment, dashboards, and inside instruments. With Streamlit, builders can create net apps utilizing Python with out frontend expertise in HTML, CSS, or JavaScript.
Its key options embody widgets for person enter, built-in caching for efficiency optimisation, and straightforward integration with information science libraries like Pandas, Matplotlib, and TensorFlow. Streamlit is especially widespread amongst information scientists and AI/ML practitioners for sharing insights and fashions in a web-based interface.
Should you’d wish to be taught extra about Streamlit, I’ve written a TDS article on utilizing it to create an information 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 check in to functions utilizing their current credentials from identification suppliers like Google, Microsoft, Okta, and Auth0.
It permits single sign-on (SSO) and gives person identification data 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 a normal for safe, scalable, and user-friendly login experiences throughout net and cellular functions.
On this article, I’ll present you tips on how to set issues up and write code for a Streamlit app that makes use of OIDC to immediate on your Google e mail and password. You should utilize these particulars to log in to the app and entry a second display that comprises an instance of an information dashboard.
Stipulations
As this text focuses on utilizing Google as an identification supplier, for those who don’t have already got one, you’ll want a Google e mail handle and a Google Cloud account. After you have your e mail, check in to Google Cloud with it utilizing the hyperlink under.
https://console.cloud.google.com
Should you’re nervous concerning the expense of signing up for Google Cloud, don’t be. They provide a free 90-day trial and $300 price of credit. You solely pay for what you utilize, and you’ll 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 price. Nevertheless, I at all times suggest organising billing alerts for any cloud supplier you join — simply in case.
We’ll return to what you should do to arrange your cloud account later.
Establishing our dev setting
I’m creating utilizing WSL2 Ubuntu Linux on Home windows, however the next must also work on common Home windows. Earlier than beginning a challenge like this, I at all times create a separate Python improvement setting the place I can set up any software program wanted and experiment with coding. Now, something I do on this setting can be siloed and received’t influence my different tasks.
I take advantage of Miniconda for this, however you should utilize any methodology that fits you finest. If you wish to observe the Miniconda route and don’t have already got it, you should first set up Miniconda.
Now, you’ll be able to arrange your setting 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 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 important to do first on the Google Cloud. They’re fairly easy, 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 simply’ll be creating a brand new challenge on your work.
Go to Google Cloud Console and log in. You need to see a display much like the one proven under.
That you must arrange a challenge first. Click on the Undertaking Picker button. It’s instantly to the best of the Google Cloud emblem, close to the highest left of the display and can be labelled with the identify of considered one of your current tasks or “Choose a challenge” for those who don’t have an current challenge. Within the pop-up that seems, click on the New Undertaking button positioned 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 completed, your new challenge identify can be displayed subsequent to the Google Cloud emblem on the prime of the display. Subsequent, click on on the hamburger-style menu on the prime left of the web page.
- Navigate to APIs & Companies → Credentials
- Click on Create Credentials → OAuth Consumer ID
- Choose Net 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 major 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="extensive")
if "web page" not in st.session_state:
st.session_state.web page = "major"
# ——— 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"
# ——— Predominant & Dashboard Pages ———
def major():
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 = "major"
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 == "major":
major()
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 “major” display or the “dashboard.”
- Auth helpers
_user_obj()
safely seize thest.person
object if it exists.user_is_logged_in()
anduser_name()
. Examine whether or not you’ve logged in and get your identify (or default to “Visitor”).
- Predominant vs. Dashboard pages
- Predominant: Should you’re not logged in, show a title/subheader prompting you to log in; for those who’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
- Exhibits a Login or Logout button relying in your standing (calling
st.login("google")
orst.logout()
). - Exhibits a “Dashboard” button that’s solely enabled when you’re logged in.
- Exhibits a Login or Logout button relying in your standing (calling
- Web page dispatch
- On the backside, it checks
st.session_state.web page
and runs bothmajor()
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 ought 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 must always now be capable of run our app. To do this, return to the folder the place app.py lives and kind this into the command line.
(streamlit) $ streamlit run app.py
If all has gone nicely along with your code and set-up, you need to see the next display.

Discover that the Dashboard button on the sidebar ought to be greyed out since you’re not logged in but. Begin by clicking the Login button on the sidebar. You need to see the display 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 if you click on it, you need to see a display 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 accessible to Streamlit customers. This lets you make sure that anybody utilizing your app is a legit person. Along with Google, you can too use widespread 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 accurately 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.