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
Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

Welcome to django-allauth! Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (soc

Raymond Penners 7.7k Jan 1, 2023
Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

Welcome to django-allauth! Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (soc

Raymond Penners 7.7k Jan 3, 2023
Mock authentication API that acceccpts email and password and returns authentication result.

Mock authentication API that acceccpts email and password and returns authentication result.

Herman Shpryhau 1 Feb 11, 2022
A simple username/password database authentication solution for Streamlit

TL;DR: This is a simple username/password login authentication solution using a backing database. Both SQLite and Airtable are supported.

Arvindra 49 Nov 25, 2022
A Python package, that allows you to acquire your RecNet authorization bearer token with your account credentials!

RecNet-Login This is a Python package, that allows you to acquire your RecNet bearer token with your account credentials! Installation Done via git: p

Jesse 6 Aug 18, 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
Authentication Module for django rest auth

django-rest-knox Authentication Module for django rest auth Knox provides easy to use authentication for Django REST Framework The aim is to allow for

James McMahon 878 Jan 4, 2023
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 who access the cluster. Kube OpenID Connect helps users with it's plugin to authenticate an get kubectl config.

null 7 Nov 20, 2022
FastAPI extension that provides JWT Auth support (secure, easy to use, and lightweight)

FastAPI JWT Auth Documentation: https://indominusbyte.github.io/fastapi-jwt-auth Source Code: https://github.com/IndominusByte/fastapi-jwt-auth Featur

Nyoman Pradipta Dewantara 468 Jan 1, 2023
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 5, 2023
Customizable User Authorization & User Management: Register, Confirm, Login, Change username/password, Forgot password and more.

Flask-User v1.0 Attention: Flask-User v1.0 is a Production/Stable version. The previous version is Flask-User v0.6. User Authentication and Management

Ling Thio 997 Jan 6, 2023
Customizable User Authorization & User Management: Register, Confirm, Login, Change username/password, Forgot password and more.

Flask-User v1.0 Attention: Flask-User v1.0 is a Production/Stable version. The previous version is Flask-User v0.6. User Authentication and Management

Ling Thio 916 Feb 15, 2021
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

Simple JWT 3.3k Jan 1, 2023
Simple extension that provides Basic, Digest and Token HTTP authentication for Flask routes

Flask-HTTPAuth Simple extension that provides Basic and Digest HTTP authentication for Flask routes. Installation The easiest way to install this is t

Miguel Grinberg 1.1k Jan 5, 2023
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 1, 2023
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 1.1k Jan 3, 2023
Simple yet powerful authorization / authentication client library for Python web applications.

Authomatic Authomatic is a framework agnostic library for Python web applications with a minimalistic but powerful interface which simplifies authenti

null 1k Dec 28, 2022
Django CAS 1.0/2.0/3.0 client authentication library, support Django 2.0, 2.1, 2.2, 3.0 and Python 3.5+

django-cas-ng django-cas-ng is Django CAS (Central Authentication Service) 1.0/2.0/3.0 client library to support SSO (Single Sign On) and Single Logou

django-cas-ng 347 Dec 18, 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 3, 2021