of exercise within the AI world over the previous few weeks, a latest essential announcement by Streamlit that it now helps OpenID Join (OIDC) login authentication nearly handed me by.
Person authorisation and verification could be a essential consideration for knowledge scientists, machine studying engineers, and others concerned in creating dashboards, machine studying proofs of idea (PoCs), and different purposes. Retaining doubtlessly delicate knowledge non-public 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 function 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 that you must know when creating extra advanced software program.
What’s Streamlit?
When 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 shortly. It’s broadly used for knowledge 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 consumer enter, built-in caching for efficiency optimisation, and straightforward integration with knowledge science libraries like Pandas, Matplotlib, and TensorFlow. Streamlit is especially well-liked amongst knowledge scientists and AI/ML practitioners for sharing insights and fashions in a web-based interface.
When you’d prefer 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 sign up to purposes utilizing their current credentials from id suppliers like Google, Microsoft, Okta, and Auth0.
It permits single sign-on (SSO) and supplies consumer id 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 regular for safe, scalable, and user-friendly login experiences throughout net and cellular purposes.
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 to your Google e-mail and password. You need to use these particulars to log in to the app and entry a second display screen that accommodates an instance of an information dashboard.
Stipulations
As this text focuses on utilizing Google as an id supplier, when you don’t have already got one, you’ll want a Google e-mail deal with and a Google Cloud account. Upon getting your e-mail, sign up to Google Cloud with it utilizing the hyperlink under.
https://console.cloud.google.com
When 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 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 could do to arrange your cloud account later.
Organising our dev setting
I’m growing utilizing WSL2 Ubuntu Linux on Home windows, however the next must also work on common Home windows. Earlier than beginning a undertaking like this, I all the time 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 will probably be siloed and gained’t influence my different tasks.
I take advantage of Miniconda for this, however you need to use any methodology that fits you greatest. If you wish to observe the Miniconda route and don’t have already got it, you could first set up Miniconda.
Now, you may 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 will probably be a streamlit app. Initially, there will probably be a display screen which shows the next textual content,
An instance Streamlit app displaying 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 fastidiously. 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 undertaking to your work.
Go to Google Cloud Console and log in. You need to see a display screen just like the one proven under.
You should arrange a undertaking first. Click on the Venture Picker button. It’s instantly to the best of the Google Cloud emblem, close to the highest left of the display screen and will probably be labelled with the identify of one among your current tasks or “Choose a undertaking” when you don’t have an current undertaking. Within the pop-up that seems, click on the New Venture button positioned on the prime proper. This can allow you to insert a undertaking identify. Subsequent, click on on the Create button.
As soon as that’s performed, your new undertaking identify will probably 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 major Python Streamlit app file will stay in. In there, create a file, comparable to 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="huge")
if "web page" not in st.session_state:
st.session_state.web page = "major"
# ——— Auth Helpers ———
def _user_obj():
return getattr(st, "consumer", 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 displaying 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/structure).
- Makes use of
st.session_state["page"]
to recollect whether or not you’re on the “major” display screen or the “dashboard.”
- Auth helpers
_user_obj()
safely seize thest.consumer
object if it exists.user_is_logged_in()
anduser_name()
. Verify whether or not you’ve logged in and get your identify (or default to “Visitor”).
- Predominant vs. Dashboard pages
- Predominant: When you’re not logged in, show a title/subheader prompting you to log in; when 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
- 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 must 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 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 properly together with your code and set-up, it is best to see the next display screen.

Discover that the Dashboard button on the sidebar must 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 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 whenever 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 accessible to Streamlit customers. This lets you be sure that anybody utilizing your app is a respectable consumer. Along with Google, you may as well use well-liked suppliers comparable to 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 accurately to be used on Google’s Cloud platform.
I additionally offered a pattern Streamlit app that exhibits Google authorisation in motion. Though this can be a easy app, it highlights all methods you require ought to your wants develop in complexity.