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
Basic auth for Django.

Basic auth for Django.

bichanna 2 Mar 25, 2022
Todo app with authentication system.

todo list web app with authentication system. User can register, login, logout. User can login and create, delete, update task Home Page here you will

Anurag verma 3 Aug 18, 2022
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 03, 2023
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
Skit-auth - Authorization for skit.ai's platform

skit-auth This is a simple authentication library for Skit's platform. Provides

Skit 3 Jan 08, 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
Login System Using Django

Login System Django

Nandini Chhajed 6 Dec 12, 2021
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
A Python library for OAuth 1.0/a, 2.0, and Ofly.

Rauth A simple Python OAuth 1.0/a, OAuth 2.0, and Ofly consumer library built on top of Requests. Features Supports OAuth 1.0/a, 2.0 and Ofly Service

litl 1.6k Dec 08, 2022
Awesome Django authorization, without the database

rules rules is a tiny but powerful app providing object-level permissions to Django, without requiring a database. At its core, it is a generic framew

1.6k Dec 30, 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
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
Brute force a JWT token. Script uses multithreading.

JWT BF Brute force a JWT token. Script uses multithreading. Tested on Kali Linux v2021.4 (64-bit). Made for educational purposes. I hope it will help!

Ivan Šincek 5 Dec 02, 2022
Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.

Django Two-Factor Authentication Complete Two-Factor Authentication for Django. Built on top of the one-time password framework django-otp and Django'

Bouke Haarsma 1.3k Jan 04, 2023
Provide OAuth2 access to your app

django-oml Welcome to the documentation for django-oml! OML means Object Moderation Layer, the idea is to have a mixin model that allows you to modera

Caffeinehit 334 Jul 27, 2022
Ready-to-use and customizable users management for FastAPI

FastAPI Users Ready-to-use and customizable users management for FastAPI Documentation: https://frankie567.github.io/fastapi-users/ Source Code: https

François Voron 2.4k Jan 04, 2023
A flask extension for managing permissions and scopes

Flask-Pundit A simple flask extension to organize resource authorization and scoping. This extension is heavily inspired by the ruby Pundit library. I

Anurag Chaudhury 49 Dec 23, 2022
OAuth2 goodies for the Djangonauts!

Django OAuth Toolkit OAuth2 goodies for the Djangonauts! If you are facing one or more of the following: Your Django app exposes a web API you want to

Jazzband 2.7k Jan 01, 2023
蓝鲸用户管理是蓝鲸智云提供的企业组织架构和用户管理解决方案,为企业统一登录提供认证源服务。

蓝鲸用户管理 简体中文 | English 蓝鲸用户管理是蓝鲸智云提供的企业组织架构和用户管理解决方案,为企业统一登录提供认证源服务。 总览 架构设计 代码目录 功能 支持多层级的组织架构管理 支持通过多种方式同步数据:OpenLDAP、Microsoft Active Directory(MAD)

腾讯蓝鲸 35 Dec 14, 2022
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 05, 2023