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
Imia is an authentication library for Starlette and FastAPI (python 3.8+).

Imia Imia (belarussian for "a name") is an authentication library for Starlette and FastAPI (python 3.8+). Production status The library is considered

Alex Oleshkevich 91 Nov 24, 2022
A Python inplementation for OAuth2

OAuth2-Python Discord Inplementation for OAuth2 login systems. This is a simple Python 'app' made to inplement in your programs that require (shitty)

Prifixy 0 Jan 06, 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
Django server for Travel Mate (Project: nomad)

Travel Mate Server (Project: Nomad) Django 2.0 server for Travel Mate Contribute For new feature request in the app, open a new feature request on the

Travel Mate 41 May 29, 2022
Python One-Time Password Library

PyOTP - The Python One-Time Password Library PyOTP is a Python library for generating and verifying one-time passwords. It can be used to implement tw

PyAuth 2.2k Dec 26, 2022
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 01, 2023
Social auth made simple

Python Social Auth Python Social Auth is an easy-to-setup social authentication/registration mechanism with support for several frameworks and auth pr

Matías Aguirre 2.8k Dec 24, 2022
A Login/Registration GUI Application with SQLite database for manipulating data.

Login-Register_Tk A Login/Registration GUI Application with SQLite database for manipulating data. What is this program? This program is a GUI applica

Arsalan 1 Feb 01, 2022
Boilerplate/Starter Project for building RESTful APIs using Flask, SQLite, JWT authentication.

auth-phyton Boilerplate/Starter Project for building RESTful APIs using Flask, SQLite, JWT authentication. Setup Step #1 - Install dependencies $ pip

sandhika 0 Aug 03, 2022
Luca Security Concept

Luca Security Concept This is the document source of luca's security concept. Please go here for the HTML version: https://luca-app.de/securityconcept

luca 43 Oct 22, 2022
Some scripts to utilise device code authorization for phishing.

OAuth Device Code Authorization Phishing Some scripts to utilise device code authorization for phishing. High level overview as per the instructions a

Daniel Underhay 6 Oct 03, 2022
Ready to use and customizable Authentications and Authorisation management for FastAPI âš¡

AuthenticationX 💫 Ready-to-use and customizable Authentications and Oauth2 management for FastAPI ⚡ Source Code: https://github.com/yezz123/AuthX Doc

Yasser Tahiri 404 Dec 27, 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
Social auth made simple

Python Social Auth Python Social Auth is an easy-to-setup social authentication/registration mechanism with support for several frameworks and auth pr

Matías Aguirre 2.8k Dec 24, 2022
A Python library to create and validate authentication tokens

handshake A Python library to create and validate authentication tokens. handshake is used to generate and validate arbitrary authentication tokens th

0 Apr 26, 2022
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
Kube OpenID Connect is an application that can be used to easily enable authentication flows via OIDC for a kubernetes cluster

Kube OpenID Connect is an application that can be used to easily enable authentication flows via OIDC for a kubernetes cluster. Kubernetes supports OpenID Connect Tokens as a way to identify users wh

7 Nov 20, 2022
RSA Cryptography Authentication Proof-of-Concept

RSA Cryptography Authentication Proof-of-Concept This project was a request by Structured Programming lectures in Computer Science college. It runs wi

Dennys Marcos 1 Jan 22, 2022
Out-of-the-box support register, sign in, email verification and password recovery workflows for websites based on Django and MongoDB

Using djmongoauth What is it? djmongoauth provides out-of-the-box support for basic user management and additional operations including user registrat

hao 3 Oct 21, 2021
Official implementation of the AAAI 2022 paper "Learning Token-based Representation for Image Retrieval"

Token: Token-based Representation for Image Retrieval PyTorch training code for Token-based Representation for Image Retrieval. We propose a joint loc

Hui Wu 42 Dec 06, 2022