YusufBerki / streamlit-jwt-authenticator

Apache License 2.0
11 stars 0 forks source link

Streamlit JWT Authenticator

logo.png An authentication module to add JWT authentication via API for Streamlit applications

[!WARNING]
This library is still in Alpha version and continues to be developed. It may contain security vulnerabilities, so please take this into consideration before using it in your project.

Table of Content

Installation

Install Streamlit JWT Authenticator with PyPI

pip install streamlit-jwt-authenticator

Quickstart

1. Pre-requirements

Streamlit JWT Authenticator allows you to use available JWT APIs. Therefore, make sure you have a working JWT authentication API.

example_api.png

2. Create Streamlit Application

In a quick start, the previously developed API can be added to the code block below and run.

import streamlit as st

from streamlit_jwt_authenticator import Authenticator

# Your API url to get JWT token 
api_url = "http://localhost/api/token/"

# Create Authenticator instance
authenticator = Authenticator(api_url)

# Add login form
authenticator.login()

# Check is user logged in successfully
if st.session_state["authentication_status"]:
    # Add logout form
    authenticator.logout()

This code should show you a login screen like below:

img.png

3. Use Token

When successfully logged in, the application saves all the keys in the response to the session. For example, if you have a key named access in the response of the login API, you can access it as follows:

st.session_state["access"]

The application can use this token when making requests to other APIs.

headers = {
    "Authorization":"Bearer {}".format(st.session_state["access"])
}

response = requests.post("http://localhost/your_api/", headers=headers)

Configuration

Authenticator()

To use the Authenticator class, you need to initialize an instance with the necessary parameters:

from streamlit_jwt_authenticator import Authenticator

authenticator = Authenticator(url="your_authentication_endpoint", headers={"Content-Type": "application/json"})

Parameters:

Authenticator.login

The login method is used to display a login form and handle user authentication. By default, it is configured to be used within a Streamlit application.

from streamlit_jwt_authenticator import Authenticator

authenticator = Authenticator(...)
authenticator.login()

Parameters:

Authenticator.logout

The logout method handles user logout by clearing authentication cookies and session state. Please check authentication_status before display logout form.

import streamlit as st

from streamlit_jwt_authenticator import Authenticator

authenticator = Authenticator(...)

if st.session_state["authentication_status"]:
    authenticator.logout()

Parameters:

License

Inspired by the Streamlit Authenticator library.

Streamlit JWT Authenticator is completely free and open-source and licensed under the Apache 2.0 license.