A secure authentication module to validate user credentials in a Streamlit application.

Overview

Streamlit-Authenticator

A secure authentication module to validate user credentials in a Streamlit application.

Installation

Streamlit-Authenticator is distributed via PyPI:

pip install streamlit-authenticator

Example

Using Streamlit-Authenticator is as simple as importing the module and using it to verify your predefined users' credentials.

import streamlit as st
import streamlit_authenticator as stauth
  • Initially define your users' names, usernames, and plain text passwords.
names = ['John Smith','Rebecca Briggs']
usernames = ['jsmith','rbriggs']
passwords = ['123','456']
  • Then use the hasher module to convert the plain text passwords to hashed passwords.
hashed_passwords = stauth.hasher(passwords).generate()
  • Subsequently use the hashed passwords to create an authentication object. Here you will need to enter a name for the JWT cookie that will be stored on the client's browser and used to reauthenticate the user without re-entering their credentials. In addition, you will need to provide any random key to be used to hash the cookie's signature. Finally, you will need to specify the number of days to use the cookie for, if you do not require passwordless reauthentication, you may set this to 0.
authenticator = stauth.authenticate(names,usernames,hashed_passwords,
    'some_cookie_name','some_signature_key',cookie_expiry_days=30)
  • Then finally render the login module as follows. Here you will need to provide a name for the login form, and specify where the form should be located i.e. main body or sidebar (will default to main body).
name, authentication_status = authenticator.login('Login','main')

  • You can then use the returned name and authentication status to allow your verified user to proceed to any restricted content.
if authentication_status:
    st.write('Welcome *%s*' % (name))
    st.title('Some content')
elif authentication_status == False:
    st.error('Username/password is incorrect')
elif authentication_status == None:
    st.warning('Please enter your username and password')
  • Should you require access to the persistent name and authentication status variables, you may retrieve them through Streamlit's session state using st.session_state['name'] and st.session_state['authentication_status']. This way you can use Streamlit-Authenticator to authenticate users across multiple pages.
if st.session_state['authentication_status']:
    st.write('Welcome *%s*' % (st.session_state['name']))
    st.title('Some content')
elif st.session_state['authentication_status'] == False:
    st.error('Username/password is incorrect')
elif st.session_state['authentication_status'] == None:
    st.warning('Please enter your username and password')

Or prompt an unverified user to enter a correct username and password.

Please note that logging out will revert the authentication status to None and will delete the associated reauthentication cookie as well.

Credits

Comments
  • Implementing a

    Implementing a "register user" fails

    I've added a widget to allow user to register (per the doc): try: if authenticator.register_user('Register user', preauthorization=False): st.success('User registered successfully') except Exception as e: st.error(e)

    But when loading the app, I get: "Pre-authorization argument must not be None"

    streamlit == 1.9.2 streamlit-authenticator == 0.2.1 OS == Ubuntu 16.04 Python == 3.6.13

    Screen Shot 2022-11-30 at 6 18 04 PM

    opened by daytonjones 5
  • ValueError: Please enter hashed passwords... even though it is already hashed.

    ValueError: Please enter hashed passwords... even though it is already hashed.

    First of all, thanks for the awesome module. I get this error even though the password I used is hashed. I can login just fine on the second attempt though.

    ValueError: Please enter hashed passwords and not plain text passwords into the 'authenticate' module.
    Traceback:
    File "/Users/server/opt/miniconda3/envs/parakeet/lib/python3.9/site-packages/streamlit/script_runner.py", line 379, in _run_script
        exec(code, module.__dict__)
    File "/Users/server/Parakeet/main.py", line 64, in <module>
        main()
    File "/Users/server/Parakeet/main.py", line 54, in main
        draw_sidebar()
    File "/Users/server/Parakeet/main.py", line 41, in draw_sidebar
        name, authentication_status = authenticator.login('Login','sidebar')
    File "/Users/server/opt/miniconda3/envs/parakeet/lib/python3.9/site-packages/streamlit_authenticator/__init__.py", line 188, in login
        raise ValueError("Please enter hashed passwords and not plain text passwords into the 'authenticate' module.")
    
    opened by Lodimup 5
  • Reuse username after login

    Reuse username after login

    Hi,

    Do you know how it would be possible to reuse the username after the user logins? I want to pass it onto a query to search in a pandas dataframe so I can display information pertaining only to that user.

    Thanks,

    opened by pelguetat 5
  • st.button calling authenticator.forgot_username returns None and empty tuple

    st.button calling authenticator.forgot_username returns None and empty tuple

    Still learning streamlit, so maybe a newbie question: Following your README example, I create the streamlit_local_auth.py As you can see from the code, I use a st.button to call forgot_username_button method.

    def forgot_username_button(auth):
        try:
            username_forgot_username, email_forgot_username = auth.forgot_username('Find my username')
    
            if username_forgot_username:
                return st.success('Username sent securely')
                # Username to be transferred to user securely
            elif username_forgot_username == False:
                return st.error('Email not found')
            print(username_forgot_username, email_forgot_username)
        except Exception as e:
            return st.error(e)
        
    
    if not authentication_status:
        if st.button("forgot username"):
            forgot_username_button(authenticator)
    
    

    Unfortunately, it seems username_forgot_username, email_forgot_username returned from auth.forgot_username method are somehow None and ""(empty string). Even if I pass authenticator as a parameter!

    Please help. Thx a lot!

    opened by cmskzhan 4
  • NameError: name 'SafeLoader' is not defined

    NameError: name 'SafeLoader' is not defined

    ymal config loader might depreciated? I try running the code and there's an error about "Loader=SafeLoader" I switch to new code below and found working.

    with open('user.ymal') as file: # config = yaml.load(file, Loader=SafeLoader) # previous code, not working config = yaml.safe_load(file) # new code (working)

    SNAG-0087

    opened by jitvimol 4
  • Customize

    Customize "Username", "Password", "Login"

    Hi @mkhorasani, thanks a lot for maintaining this awesome module! I'd like to be able to customize the labels for the two text_inputs and for the button. Specifically, I'd make them lower caps so that they fit in with the rest of the naming pattern in the screenshot below. I could do a PR myself, as I feel there are literally 4 lines of code to change. Let me know what you think!

    # current
    name, authentication_status = authenticator.login('login', 'sidebar')
    
    # suggestion
    name, authentication_status = authenticator.login('login', 'sidebar', 'username', 'password', 'login') # where the new ones have defaults
    

    Edit: Same for "Logout" would be nice, too.

    Screenshot from 2022-01-06 10-16-41

    opened by paulbricman 4
  • Newer version breaks with cookies from old version

    Newer version breaks with cookies from old version

    Hi, I was using version 0.1.0, and when updated to version 0.1.4, because I and other users already have some cookies in the browsers, the code breaks when it tries to access the field username from the cookies.

    The traceback is

    File "/code/app/utils/misc.py", line 35, in authentication_workflow
        name, authentication_status, username = authenticator.login("Login", "sidebar")
    File "/usr/local/lib/python3.8/site-packages/streamlit_authenticator/__init__.py", line 163, in login
        st.session_state['username'] = self.token['username']
    
    opened by charlielito 3
  • auth with st.set_page_config

    auth with st.set_page_config

    When i define code for authentication in my def main() in wihch st.set_page_config(layout="wide"). My app not working. def main(): names = ['John Smith','Rebecca Briggs'] usernames = ['jsmith','rbriggs'] passwords = ['123','456'] hashed_passwords = stauth.Hasher(passwords).generate() authenticator = stauth.Authenticate(names,usernames,hashed_passwords, 'some_cookie_name','some_signature_key',cookie_expiry_days=30) name, authentication_status, username = authenticator.login('Login','main')

    if authentication_status:
        current_plan = data.get_current_capacity_plan()
        setup_multipage(current_plan)
        refresher.start()
    elif authentication_status == False:
        st.error('Username/password is incorrect')
    elif authentication_status == None:
        st.warning('Please enter your username and password')
    
    st.set_page_config(
        page_title='app_name',
        layout='wide',
    ) 
    

    That in error trace
    StreamlitAPIException: set_page_config() can only be called once per app, and must be called as the first Streamline command in your script.

    when st.set_page_config is commented out everything works

    ideas? i dont understand where st.set_page_config can called. Or how i can define default page config for authentication

    opened by nfomin99 3
  • Not able to create a new account using register_user

    Not able to create a new account using register_user

    I am new to streamlit. I want to have a login and signup functionality in my application. I am able to successfully implement login using the username and password stored in the config.yaml file. However, I am not able to properly implement the register_user or reset/update the password. The program runs smoothly and I get the 'registration successful' message but when I try to log in using the new credentials I get the 'incorrect username/password' error.

    image

    image

    opened by poojanaik08 2
  • [Question] How to use st.set_page_config(layout=

    [Question] How to use st.set_page_config(layout="wide") without user/pass elements taking up the full width.

    Via: https://docs.streamlit.io/library/api-reference/utilities/st.set_page_config you can set the width to be "Wide" by default. This causes the user/pass elements to also load into this full width which is a stange UI/UX for a login interface. Any ideas how to over-ride this into some smaller width component?

    opened by KeeonTabrizi 2
  • What's the recommended way to store login info as secrets?

    What's the recommended way to store login info as secrets?

    Using a yaml>toml converter it's possible to store the entire yaml configuration as a secret using streamlit cloud, which works as expected.

    For deploying from other services, how can leverage environment variables?

    opened by batmanscode 2
  • yaml.SafeLoader

    yaml.SafeLoader

    It may be confusing for the user to determine where to import SafeLoader, as .load is called with yaml.load. To avoid confusion, it would be better to use yaml.SafeLoader.

    opened by TheHamkerCat 0
  • Allow Domain Access + Full Widget

    Allow Domain Access + Full Widget

    This PR does a few things:

    • Allows users to allow a specific domain and users by individual email addresses.
    • It also includes a function that allows users to create all the forms within a single tab.
    • Includes a connection to Deta as a data store, storing user credentials on the cloud instead of locally on a disk.
    • Updates the readme with all the needed information to get started.

    Issues: https://github.com/mkhorasani/Streamlit-Authenticator/issues/43, https://github.com/mkhorasani/Streamlit-Authenticator/issues/42

    opened by abdulrabbani00 1
  • Feature - Only allow users within a certain domain to create an account

    Feature - Only allow users within a certain domain to create an account

    Small lift here. But it would be great if we could define who can create a user account. This would allow users to make a streamlit application public, and then allow everyone from their organization to create individual accounts.

    Also happy to integrate this if you are willing to accept it :D

    opened by abdulrabbani00 0
  • Feature - Store YAML file in a remote data store

    Feature - Store YAML file in a remote data store

    It would be terrific is the user credentials could be stored in a remote data store (Deta, Mongo, etc).

    I would be happy to integrate this feature if you are interested in having it incorporated.

    opened by abdulrabbani00 2
  • Can I block a new login, when a user is already logged in?

    Can I block a new login, when a user is already logged in?

    Hello, I have a streamlit webapp that uses streamlit-authenticator and it works just fine, but we have seen some 'collisions' when two users are logged in a the same time (same variable names, different values, erase each other temporary files, and so on). Is there a way to block the new login to be sure that only one user can login at the same time?

    opened by alicjagrocholska 5
  • Return user email, Name for new user

    Return user email, Name for new user

    Hi, Is there a way that we can get the email address and the name of the newly registered user without modifying the package code. Currently is returns if a new user has successfully created account or not.

    opened by psyrixen 3
Releases(v0.2.1)
Owner
M Khorasani
Hybrid of a data scientist and an engineer. Founder of DummyLearn.com a free online machine learning platform.
M Khorasani
Implements authentication and authorization as FastAPI dependencies

FastAPI Security Implements authentication and authorization as dependencies in FastAPI. Features Authentication via JWT-based OAuth 2 access tokens a

Jacob Magnusson 111 Jan 07, 2023
Simple Login - Login Extension for Flask - maintainer @cuducos

Login Extension for Flask The simplest way to add login to flask! How it works First, install it from PyPI: $ pip install flask_simplelogin Then, use

Flask Extensions 181 Jan 01, 2023
Flask user session management.

Flask-Login Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering your users

Max Countryman 3.2k Dec 28, 2022
Django-react-firebase-auth - A web app showcasing OAuth2.0 + OpenID Connect using Firebase, Django-Rest-Framework and React

Demo app to show Django Rest Framework working with Firebase for authentication

Teshank Raut 6 Oct 13, 2022
Minimal authorization through OO design and pure Ruby classes

Pundit Pundit provides a set of helpers which guide you in leveraging regular Ruby classes and object oriented design patterns to build a simple, robu

Varvet 7.8k Jan 02, 2023
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.2k Dec 29, 2022
This is a Python library for accessing resources protected by OAuth 2.0.

This is a client library for accessing resources protected by OAuth 2.0. Note: oauth2client is now deprecated. No more features will be added to the l

Google APIs 787 Dec 13, 2022
An open source Flask extension that provides JWT support (with batteries included)!

Flask-JWT-Extended Features Flask-JWT-Extended not only adds support for using JSON Web Tokens (JWT) to Flask for protecting views, but also many help

Landon Gilbert-Bland 1.4k Jan 04, 2023
PetitPotam - Coerce NTLM authentication from Windows hosts

Python implementation for PetitPotam

ollypwn 137 Dec 28, 2022
A host-guest based app in which host can CREATE the room. and guest can join room with room code and vote for song to skip. User is authenticated using Spotify API

A host-guest based app in which host can CREATE the room. and guest can join room with room code and vote for song to skip. User is authenticated using Spotify API

Aman Raj 5 May 10, 2022
A wagtail plugin to replace the login by an OAuth2.0 Authorization Server

Wagtail OAuth2.0 Login Plugin to replace Wagtail default login by an OAuth2.0 Authorization Server. What is wagtail-oauth2 OAuth2.0 is an authorizatio

Gandi 7 Oct 07, 2022
A simple Boilerplate to Setup Authentication using Django-allauth 🚀

A simple Boilerplate to Setup Authentication using Django-allauth, with a custom template for login and registration using django-crispy-forms.

Yasser Tahiri 13 May 13, 2022
Abusing Microsoft 365 OAuth Authorization Flow for Phishing Attack

Microsoft365_devicePhish Abusing Microsoft 365 OAuth Authorization Flow for Phishing Attack This is a simple proof-of-concept script that allows an at

Optiv Security 76 Jan 02, 2023
Flask JWT Router is a Python library that adds authorised routes to a Flask app.

Read the docs: Flask-JWT-Router Flask JWT Router Flask JWT Router is a Python library that adds authorised routes to a Flask app. Both basic & Google'

Joe Gasewicz 52 Jan 03, 2023
Foundation Auth Proxy is an abstraction on Foundations' authentication layer and is used to authenticate requests to Atlas's REST API.

foundations-auth-proxy Setup By default the server runs on http://0.0.0.0:5558. This can be changed via the arguments. Arguments: '-H' or '--host': ho

Dessa - Open Source 2 Jul 03, 2020
Creation & manipulation of PyPI tokens

PyPIToken: Manipulate PyPI API tokens PyPIToken is an open-source Python 3.6+ library for generating and manipulating PyPI tokens. PyPI tokens are ver

Joachim Jablon 8 Nov 01, 2022
Simple implementation of authentication in projects using FastAPI

Fast Auth Facilita implementação de um sistema de autenticação básico e uso de uma sessão de banco de dados em projetos com tFastAPi. Instalação e con

3 Jan 08, 2022
Easy and secure implementation of Azure AD for your FastAPI APIs 🔒 Single- and multi-tenant support.

Easy and secure implementation of Azure AD for your FastAPI APIs 🔒 Single- and multi-tenant support.

Intility 220 Jan 05, 2023
This is a Token tool that gives you many options to harm the account.

Trabis-Token-Tool This is a Token tool that gives you many options to harm the account. Utilities With this tools you can do things as : ·Delete all t

Steven 2 Feb 13, 2022
JWT authentication for Pyramid

JWT authentication for Pyramid This package implements an authentication policy for Pyramid that using JSON Web Tokens. This standard (RFC 7519) is of

Wichert Akkerman 73 Dec 03, 2021