Machine Learning

User authorization in streamlit with OIDC and Google

For a job in World Ai in the last few weeks, the latest announcement is steering that we now support the Openid Connect Connect (OIDC) confirmation now.

User authorization and verification can be important considerations of information in detail, equipment learning engineers, and other participants in creating the Dashboard, the proof of the learning of the Mental Device (POCS), and other applications. Saving potential private data is very important, so you want to ensure that only authorized users can access your application.

In this article, we will discuss this new feature of streamlit and improve a simple app to show. Our app can be easy, but shows all the important things you need to know when creating complex software.

What is guidance?

If you have never heard in order, it is a Library open Python library designed to build and submit effective web apps with a small code immediately. Data recognition is widely used, shipment of a model for a machine learning, device, dashboard, and internal tools. With streamlit, enhancements can create web applications using the Python without previous experience in HTML, CSS, or JavaScript.

Its important features include the user's installation widgets, built-in-for-functioning widgets, as well as simple combinations with scientific libraries such as pandas, matplotlib, and tensorflow. Streamlit is popular with data scientists and AI / ML by sharing information and visual models based on web.

If you would like to learn more about streamlit, I have written a TDS article to use the data dashboard, which you can find using This link.

What is OIDC?

OpenID Connect (OIDC) is the verification protocol that forms Oauuth 2.0. It allows users to safety on requests using their existing authenticity from ID providers such as Google, Microsoft, OkTA, and Author0.

It enables one login (SSO) and provides user's identity document information with id tokens, including email addresses and profile details. Unlike the oauth, focused on the authorization, the OIDC is clearly intended for authentication, which makes it as a safe, visible, easy-to-use login on all web and mobile apps.

In this article, I will show you how to set things and write the sallistit application code using the OIDC to speed up your email and password. You can use that information to access the app and access the second screen containing an example of the data dashboard.

Requirements

As this article focuses on using Google as a ID provider, if you do not have one, you will need Google email address and Google Cloud account. If you have your email, sign in to Google Cloud also using the link below.

If you are worried about the cost of subscriber to Google's cloud, do not. They give 90 days test and $ 300 relevant credits. You pay only what you use, and you can cancel your Cloud account at any time, before or after free expiry. No matter what we will do here should decide. However, I always recommend to set billing alerts in any subscriber provider – in case.

We will return to what you should do to set up your cloud account later.

Setting up our dev

I create WSL2 Linux personality in the windows, but the following should also apply to normal windows. Before starting a project like this, I always create a different Psyth Development area where I can install any software needed and check the codes. Now, whatever I do in this place will be quoted and not touching other projects.

I am using a miniconda for this, but you can use any method that suits you. If you want to follow a minicondond route and you don't have any one you have, you should first add a minicondonda.

Now, you can set your environment like this.

(base) $ conda create -n streamlit python=3.12 -y
(base) $ conda activate streamlit
# Install required Libraries
(streamlit) $ pip install streamlit  streamlit-extras Authlib 
(streamlit) $ pip install pandas matplotlib numpy

What will we build

This will be a broadcast application. At first, there will be a screen that shows the following text,

Example Offering an Application Application Displays OIDC and Google Email Concolution

Please use a side bar button to log in.

Next to the left, there will be two buttons. Another means Sign in, and another says Dipboard.

If the user does not log in, Dashboard button will be released and is not available for use. When the user presses the login button, the screen will be displayed for user to sign in with Google. If you are logged in, two things happen: –

  • This page Login Button on side changes Get out.
  • This page Dipboard Button is available for use. This will show some dummy data and graphs now.

If clicking the user you log in Exit Button, the app reset to its original position.

Nb. I sent the active version of my app in the streamlit community. Sneak Preview, click the link below. You may need “resurrecting” app starts when no one clicked on it for a while, but this takes a few seconds.

Set to Google Cloud

Enabling Email Verification using your Google Gmail account, there are only a few things to do first in Google's cloud. They understand exactly, so take your time and follow each step carefully. I think you have already set or have email email and a cloud account, and that you will create a new job for your work.

Go to Google Cloud console and log in. You must see the same screen similar to the one shown below.

Photo by the writer

You need to set up the project first. Click This page The Choice of Project button. Marched to Google Cloud logo, next to the top left of the screen and will be written in the name of one of your existing projects or “Choose a project“If you do not have an existing project. In Pop-up from, click New project Button found to the upper right. This will allow you to enter a project name. Next, click Cause button.

When that is finished, your new project name will be displayed near Google's cloud at the top of the screen. Next, click on the hamburger style menu on the top left of the page.

  • Navigate to APIs and Services → Conquerors
  • Click Create Conquering → The OAUTHL's Cell ID
  • Designate Application for web
  • Add as a Redirecting Authorized URI
  • Note the Client ID including Customer's Secret As we will need them a little.

Local setting and Python code

Decide which place folder of your main location of the Python Streamlit App will last. There, create a file, such as app.py, and enter the following Python code to.

import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# ——— Page setup & state ———
st.set_page_config(page_title="SecureApp", page_icon="🔑", layout="wide")

if "page" not in st.session_state:
    st.session_state.page = "main"

# ——— Auth Helpers ———
def _user_obj():
    return getattr(st, "user", 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, "name", "Guest") if u else "Guest"

# ——— Main & Dashboard Pages ———
def main():
    if not user_is_logged_in():
        st.title("An example Streamlit app showing the use of OIDC and Google email for login authentication")
        st.subheader("Use the sidebar button to log in.")
    else:
        st.title("Congratulations")
        st.subheader("You’re logged in! Click 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"],
        "Sales": np.random.randint(100,500,6),
        "Profit": np.random.randint(20,100,6)
    })
    st.dataframe(df)

    fig, ax = plt.subplots()
    ax.plot(df["Month"], df["Sales"], marker="o", label="Sales")
    ax.set(xlabel="Month", ylabel="Sales", title="Monthly Sales Trend")
    ax.legend()
    st.pyplot(fig)

    fig, ax = plt.subplots()
    ax.bar(df["Month"], df["Profit"], label="Profit")
    ax.set(xlabel="Month", ylabel="Profit", title="Monthly Profit")
    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.page = "main"
        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.page = "dashboard"
    st.rerun()

# ——— Page Dispatch ———
if st.session_state.page == "main":
    main()
else:
    dashboard()

This document creates a two-papper app with a group of Google (or OIDC) to log in and simple dashboard:

  1. To Set Up Page and Province
    • To configure the browser tab (title / icon / structure).
    • Use st.session_state["page"] Remembering that you are on the screen “Main” or “Dashboard.”
  2. Authors of the author
    • _user_obj() Giba gt safe st.user something if it is.
    • user_is_logged_in() including user_name(). Check if you are logged in and get your name (or default in “guest”).
  3. Main VS Dashboard Pages
    • Potent: If you do not log in, show theme / subtitle that moves you to login; When logged in, show message to congratulate and direct the dashboard.
    • Dipboard: Greeting by name, production Dummy Databame for sales / monthly profit, indicate, and give a line chart for sales and bar chart.
  4. Sidebar Navigation
    • Displays login or login button depends on your status (beating st.login("google") or st.logout()).
    • Displays the “Dashboard” button to be enabled only if you are logged in.
  5. Page Shipment
    • Below, it is exploring st.session_state.page and works or main() or dashboard() rightly.

To prepare your secrets.toml With the truth of Google Oauth

Same lilder when your app.py file life, create a folder called .Streamlit. Now go in this new ones and create a file called Secrets.Toml. This page Client ID including Customer's Secret From Google's cloud should be added to that file, as well as a secret redirected URI and Cookie secret. Your file should look at something like this,

#
# secrets.toml 
#
[auth]
redirect_uri = ""
cookie_secret = "your-secure-random-string-anything-you-like"

[auth.google]
client_id = "************************************.apps.googleusercontent.com"
client_secret = "*************************************"
server_metadata_url = "

All right, now we have to be able to use our app. To do that, return to a folder where the app survives and type this in the command line.

(streamlit) $ streamlit run app.py

If you all go well with your code and setup, you should see the next screen.

Photo by the writer

Note that the Dashboard button in a separate bar should be issued because you do not sign in. Start by clicking the login button in a separate bar. You should see the bottom screen (I hide my guarantees for security reasons),

Photo by the writer

When choosing an account and logging in, Streamlit application will change from this.

Photo by the writer

You will also know that Dashboard button now clicks, and when you click, you should see a screen like this.

Photo by the writer

Finally, fucking out, and the app should go back to its original state.

Summary

In this article, I explained that the appropriate ODC authorization is now available for effective users. This allows you to make sure anyone uses your app is a formal user. In addition to Google, you can also use famous providers such as Microsoft, Oauth, Oceta, and others.

I have described any broadcasts and use, and briefly define Openid Connect Connect Connect (OIDC) Protocol Protocol.

My example is to focus on using Google as a guarantee and show you the necessary steps to set up properly for use in the Google platform.

I also also provided a broadcasting sample app that displays Google Authorization. Although this is a simple app, it highlights all the strategies you need if your needs increase.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button