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.
Person 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 functions. Maintaining doubtlessly 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 could be easy, but it surely demonstrates all the important thing issues you must know when creating extra advanced software program.
What’s Streamlit?
If you happen to’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 in style amongst information scientists and AI/ML practitioners for sharing insights and fashions in a web-based interface.
If you happen to’d wish to study extra about Streamlit, I’ve written a TDS article on utilizing it to create an information dashboard, which you’ll 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 present credentials from identification suppliers like Google, Microsoft, Okta, and Auth0.
It allows single sign-on (SSO) and gives person identification data through 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 the way to set issues up and write code for a Streamlit app that makes use of OIDC to immediate in your Google e mail and password. You should utilize these particulars to log in to the app and entry a second display that incorporates an instance of an information dashboard.
Conditions
As this text focuses on utilizing Google as an identification supplier, if you happen to don’t have already got one, you’ll want a Google e mail deal with and a Google Cloud account. After getting your e mail, check in to Google Cloud with it utilizing the hyperlink beneath.
https://console.cloud.google.com
If you happen to’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 employ, 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 value. Nevertheless, I all the time advocate establishing 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.
Organising our dev atmosphere
I’m growing utilizing WSL2 Ubuntu Linux on Home windows, however the next must also work on common Home windows. Earlier than beginning a venture like this, I all the time create a separate Python improvement atmosphere the place I can set up any software program wanted and experiment with coding. Now, something I do on this atmosphere will probably be siloed and received’t impression my different tasks.
I exploit Miniconda for this, however you should use any technique that fits you finest. If you wish to comply with the Miniconda route and don’t have already got it, you should first set up Miniconda.
Now, you may 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 will probably be a streamlit app. Initially, there will probably 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 simple, so take your time and comply with 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 venture in your work.
Go to Google Cloud Console and log in. It’s best to see a display much like the one proven beneath.
You could arrange a venture first. Click on the Undertaking Picker button. It’s instantly to the suitable of the Google Cloud emblem, close to the highest left of the display and will probably be labelled with the title of one in every of your present tasks or “Choose a venture” if you happen to don’t have an present venture. Within the pop-up that seems, click on the New Undertaking button situated on the high proper. It will allow you to insert a venture title. Subsequent, click on on the Create button.
As soon as that’s carried out, your new venture title will probably be displayed subsequent to the Google Cloud emblem on the high of the display. Subsequent, click on on the hamburger-style menu on the high left of the web page.
- Navigate to APIs & Providers → Credentials
- Click on Create Credentials → OAuth Shopper ID
- Choose Internet software
- Add http://localhost:8501/oauth2callback as an Licensed Redirect URI
- Pay attention to the Shopper ID and Shopper 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 reside 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="🔑", structure="vast")
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, "title", "Visitor") if u else "Visitor"
# ——— Principal & 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 Pattern")
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/structure).
- Makes use of
st.session_state["page"]
to recollect whether or not you’re on the “principal” display or the “dashboard.”
- Auth helpers
_user_obj()
safely seize thest.person
object if it exists.user_is_logged_in()
anduser_name()
. Verify whether or not you’ve logged in and get your title (or default to “Visitor”).
- Principal vs. Dashboard pages
- Principal: If you happen to’re not logged in, show a title/subheader prompting you to log in; if you happen to’re logged in, show a congratulatory message and direct you to the dashboard.
- Dashboard: greets you by title, 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 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 Shopper ID and Shopper 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 to run our app. To try 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 effectively together with your code and set-up, you need to see the next display.

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’s best to see the display beneath (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 whenever 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 be sure that anybody utilizing your app is a respectable person. Along with Google, you may also use in style 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 targeted 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 offered a pattern Streamlit app that exhibits Google authorisation in motion. Though it is a easy app, it highlights all strategies you require ought to your wants develop in complexity.