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
Two factor authentication system using azure services and python language and its api's

FUTURE READY TALENT VIRTUAL INTERSHIP PROJECT PROJECT NAME - TWO FACTOR AUTHENTICATION SYSTEM Resources used: * Azure functions(python)

BHUSHAN SATISH DESHMUKH 1 Dec 10, 2021
Authentication with fastapi and jwt cd realistic

Authentication with fastapi and jwt cd realistic Dependencies bcrypt==3.1.7 data

Fredh Macau 1 Jan 04, 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
Auth-Starters - Different APIs using Django & Flask & FastAPI to see Authentication Service how its work

Auth-Starters Different APIs using Django & Flask & FastAPI to see Authentication Service how its work, and how to use it. This Repository based on my

Yasser Tahiri 7 Apr 22, 2022
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
Authentication, JWT, and permission scoping for Sanic

Sanic JWT Sanic JWT adds authentication protection and endpoints to Sanic. It is both easy to get up and running, and extensible for the developer. It

Adam Hopkins 229 Jan 05, 2023
Login-python - Login system made in Python, using native libraries

login-python Sistema de login feito 100% em Python, utilizando bibliotecas nativ

Nicholas Gabriel De Matos Leal 2 Jan 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
An extension of django rest framework, providing a configurable password reset strategy

Django Rest Password Reset This python package provides a simple password reset strategy for django rest framework, where users can request password r

Anexia 363 Dec 24, 2022
Auth for use with FastAPI

FastAPI Auth Pluggable auth for use with FastAPI Supports OAuth2 Password Flow Uses JWT access and refresh tokens 100% mypy and test coverage Supports

David Montague 95 Jan 02, 2023
Cack facebook tidak login

Cack facebook tidak login

Angga Kurniawan 5 Dec 12, 2021
Simplifying third-party authentication for web applications.

Velruse is a set of authentication routines that provide a unified way to have a website user authenticate to a variety of different identity provider

Ben Bangert 253 Nov 14, 2022
Django Rest Framework App wih JWT Authentication and other DRF stuff

Django Queries App with JWT authentication, Class Based Views, Serializers, Swagger UI, CI/CD and other cool DRF stuff API Documentaion /swagger - Swa

Rafael Salimov 4 Jan 29, 2022
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
Use this to create (admin) personal access token in gitlab database. Mainly used for automation.

gitlab-personal-access-token Ensure PAT is present in gitlab database. This tool is mainly used when you need to automate gitlab installation and conf

CINAQ Internet Technologies 1 Jan 30, 2022
OAuthlib support for Python-Requests!

Requests-OAuthlib This project provides first-class OAuth library support for Requests. The OAuth 1 workflow OAuth 1 can seem overly complicated and i

1.6k Dec 28, 2022
A module making it easier to manage Discord oAuth with Quart

quart_discord A module making it easier to manage Discord oAuth with Quart Install pip install git+https://github.com/xelA/ 5 Oct 27, 2022

Django Admin Two-Factor Authentication, allows you to login django admin with google authenticator.

Django Admin Two-Factor Authentication Django Admin Two-Factor Authentication, allows you to login django admin with google authenticator. Why Django

Iman Karimi 9 Dec 07, 2022
Storefront - A store App developed using Django, RESTFul API, JWT

Storefront A store App developed using Django, RESTFul API, JWT. SQLite has been

Muhammad Algshy 1 Jan 07, 2022
User Authentication in Flask using Flask-Login

User-Authentication-in-Flask Set up & Installation. 1 .Clone/Fork the git repo and create an environment Windows git clone https://github.com/Dev-Elie

ONDIEK ELIJAH OCHIENG 31 Dec 11, 2022