Socket
Socket
Sign inDemoInstall

streamlit-ldap-authenticator

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

streamlit-ldap-authenticator

Authenticate using ldap


Maintainers
1

Welcome to Streamlit LDAP Authenticator 🔑

PyPI Download GitHub GitHub license GitHub issues GitHub pull requests

A fast and easy way to handle the user authentication using ldap in your Streamlit apps.

What is Streamlit LDAP Authenticator?

streamlit-ldap-authenticator let you add login form and execute authentication before your streamlit page app started.

Features

  • Authentication using active directory.
  • Each page app can have it's own additional user authorization.
  • User login status will share across multi page app by making use of streamlit Session State
  • Can configure to remember user login by using cookie in the client's browser.

LoginForm

LogoutForm

Installation

Open a terminal and run:

pip install streamlit-ldap-authenticator

Quickstart

Simple log in example

Create a new file secrets.toml in .streamlit folder.
You can learn more about secrets management streamlit documentation.

Require Configuration

  • Active directory server path of your organization
  • Your organization domain
  • Avaliable attribute for your organization for person data in active directory. You can use ADExplorer to explore avaliable attribute for your organization.

If your organization email address is "@example.com", most likely your configuration will be as below

[ldap]
server_path = "ldap://ldap.example.com"
domain = "example"
search_base = "dc=example,dc=com"
attributes = ["sAMAccountName", "distinguishedName", "userPrincipalName", "displayName", "manager", "title"]
use_ssl = true

[session_state_names]
user = "login_user"
remember_me = "login_remember_me"

[auth_cookie]
name = "login_cookie"
key = "{any password for encryption}"
expiry_days = 1
auto_renewal = true
delay_sec = 0.1

Create a new file simple_login.py with the following code:

import streamlit as st
from streamlit_ldap_authenticator import Authenticate

# Declare the authentication object
auth = Authenticate(
    st.secrets['ldap'],
    st.secrets['session_state_names'],
    st.secrets['auth_cookie']
)

# Login Process
user = auth.login()
if user is not None:
    auth.createLogoutForm({'message': f"Welcome {user['displayName']}"})

    # Your page application can be written below
    st.write("# Welcome to my App! 👋")
    st.write(user)

Run the streamlit app!

streamlit run simple_login.py

Add Encryption module

This is recommended if you are using http protocol as http protocol doesn't encrypt when exchanging information between server and client. So anyone in the network can see the user password if it is not encrypted.

Gnerate RSA Key Pair

Create a new file generateKeys.py

from streamlit_rsa_auth_ui import Encryptor

encryptor = Encryptor.generateNew(2048)
encryptor.save('rsa', 'authkey')

Run generateKeys.py python script

python generateKeys.py

this will create a private key and public key pair

  • private key with the file name authkey
  • public key with the file name authkey.pub
├── rsa
│ ├── authkey
│ │ authkey.pub

Add Configuration

add to the secrets.toml

[encryptor]
folderPath = "rsa"
keyName = "authkey"

Change the authentication declaration code

# Declare the authentication object
auth = Authenticate(
    st.secrets['ldap'],
    st.secrets['session_state_names'],
    st.secrets['auth_cookie'],
    st.secrets['encryptor']
)

Configuration Objects

LdapConfig

Configuration for your organization active directory

NameTypeDescription
server_pathstrActive directory server path. E.g. 'ldap://ldap.example.com'
domainstrYour organization domain. E.g. 'Example'
search_basestrActive directory base search. E.g. 'dc=example, dc=com'
attributesList[str]Attribute avaliable in your organization active directory. You can reference in ADExplorer
use_sslboolDetermine whether to use basic SSL basic authentication

SessionStateConfig

Configuration for streamlit Session State key names

NameTypeDescription
userstrKey name to store user information
remember_mestrKey name to store remember_me checkbox selection

CookieConfig

Configuration to store user information to the cookie in client's browser. Thus even when user close the browser and reload the page, Reauthorization is possible with cookie.

NameTypeDescription
namestrcookie name to store in client's browser
keystrencryption key to encrypt user information
expiry_daysfloatexpiry date for the cookie
auto_renewalboolCookie will expire after defined days from the last activity when value is True. Cookie will expire after defined days from the last login when value is False.
delay_secfloatDelay in sec after set or delete cookie

EncryptorConfig

Configuration for encryption key location to encrypt user information at the client browser before send back to server.

NameTypeDescription
folderPathstrFolder location where the encryption key is stored. (Make sure the key location is private)
keyNamestrThe name of the key

TitleConfig

NameTypeDescription
textstr | NoneOptional title text
size'smaller' | 'small' | 'medium' | 'large' | 'extraLarge' | NoneOptional title size
align'left' | 'center' | 'right' | NoneOptional text alignment
argsdict | NoneOptional additional title properties can be reference in Ant Design Title

RequiredRule

NameTypeDescription
requiredboolTrue if the item is required
messagestr | NoneOptional error message if violate the required rule
warningOnlybool | NoneWarning only if True and will not block the form submit

PatternRule

NameTypeDescription
patternstrRegex pattern
messagestr | NoneOptional error message if violate the pattern rule
warningOnlybool | NoneWarning only if True and will not block the form submit

TextInputConfig

NameTypeDescription
placeholderstr | NoneOptional placeholder for text input
labelstr | NoneOptional label will be display left of text input in wide screen size and top of text input in small screen size
widthstr | NoneOptional width of the input Reference
requiredRequiredRule | bool | dict | NoneOptional required rule
patternsList[PatternRule | str | dict] | NoneOptional pattern rules
argsdict | Noneoptional additional input properties can be reference in Ant Design Input

CheckboxConfig

NameTypeDescription
labelstr | Nonelabel will be display right of checkbox
widthstr | NoneOptional width of the checkbox Reference
requiredRequiredRule | bool | dict | NoneOptional required rule
argsdict | Noneoptional additional input properties can be reference in Ant Design Checkbox

ButtonConfig

NameTypeDescription
labelstr | NoneOptional button label
widthstr | NoneOptional width of the button Reference
argsdict | NoneOptional additional button properties can be reference in Ant Design Button

SigninFormConfig

NameTypeDescription
formType'default' | 'inline' | NoneWill be 'default' if None
labelSpanint | NoneLabel Layout
wrapperSpanint | NoneLayout of the input control
maxWidthint | NoneMax form width
align'left' | 'center' | 'right' | NoneHorizontal form alignment
titleTitleConfig | str | dict | NoneConfig for title control of the form
submitButtonConfig | str | dict | NoneConfig for submit button of the form
usernameTextInputConfig | str | dict | NoneConfig for username input of the form
passwordTextInputConfig | str | dict | NoneConfig for password input of the form
rememberCheckboxConfig | str | dict | NoneConfig for remember checkbox of the form
argsdict | NoneOptional addtional form properties can be reference in Ant Design Form

SignoutFormConfig

NameTypeDescription
formType'default' | 'inline' | NoneWill be 'default' if None
maxWidthint | NoneMax form width
align'left' | 'center' | 'right' | NoneHorizontal form alignment
titleTitleConfig | str | dict | NoneConfig for title control of the form
submitButtonConfig | str | dict | NoneConfig for submit button of the form
argsdict | NoneOptional addtional form properties can be reference in Ant Design Form

Callback Extension

Addtional task can be executed upon successful login or logout
Login Process is as follow

  • Reauthenticate from Session state, if unsuccessful
  • Reauthenticate form cookie, if unsuccessful
  • Ask user input
  • Login to Active Directory
  • Execute additionalCheck argument function
  • Execute callback argument function
  • Save user info in Session state
  • Save encrypted user info in cookie

Logout Process is as follow When user click Sign out button

  • Execute callback argument function. If 'cancel' is return, will not continue
  • Delete user info from Session state
  • Delete encrypted user info in cookie

Create a new file simple_login_callback.py with the following code:

import streamlit as st
from streamlit_rsa_auth_ui import SignoutEvent
from streamlit_ldap_authenticator import Authenticate, UserInfos
from typing import Optional, Union, Literal

# Declare the authentication object
auth = Authenticate(
    st.secrets['ldap'],
    st.secrets['session_state_names'],
    st.secrets['auth_cookie']
)

def login(user: Union[UserInfos, str]) -> Optional[str]:
    st.session_state.TestSs = {"login_successful": True}

def logout(event: SignoutEvent) -> Optional[Literal['cancel']]:
    if 'TestSs' in st.session_state:
        del st.session_state.TestSs
    if 'TestSs' in st.session_state:
        return 'cancel'

# Login Process
user = auth.login(callback=login)
if user is not None:
    auth.createLogoutForm({'message': f"Welcome {user['displayName']}"}, callback=logout)

    # Your page application can be written below
    st.write("# Welcome to my App! 👋")
    st.write(user)

More Examples

Addtional check with job title after ldap authentication completed

Create a new file title_login.py with the following code:

import streamlit as st
from streamlit_ldap_authenticator import Authenticate, Connection, UserInfos
from typing import Optional

# Declare the authentication object
auth = Authenticate(
    st.secrets['ldap'],
    st.secrets['session_state_names'],
    st.secrets['auth_cookie']
)

def checkUserByTitle(conn: Optional[Connection], user: UserInfos):
    title = "Engineer"
    if user['title'].__contains__(title): return True
    return f"You are not a {title}. Not authorize to use this page."

# Login Process
user = auth.login(checkUserByTitle)
if user is not None:
    auth.createLogoutForm({'message':f"Welcome {user['displayName']}"})

    # Your page application can be written below
    st.write("# Welcome to my App! 👋")
    st.write(user)

Now run it to open the app!

streamlit run title_login.py

Additional check with reporting structure after ldap authentication completed

Create a new file report_login.py with the following code:

import streamlit as st
from streamlit_ldap_authenticator import Authenticate, Connection, UserInfos
from typing import Optional

# Declare the authentication object
auth = Authenticate(
    st.secrets['ldap'],
    st.secrets['session_state_names'],
    st.secrets['auth_cookie']
)

def __isReportTo(user: UserInfos, conn: Optional[Connection], email: str, max_level = 3, current_level = 1):
    if current_level > max_level: return False

    manager = user['manager']

    if type(manager) is str and type(conn) is Connection:
        manager = auth.ldap_auth.getInfoByDistinguishedName(conn, manager)
        user['manager'] = manager

    if type(manager) is not dict: return False
    if manager['mail'] == email: return True
    return __isReportTo(manager, conn, email, max_level, current_level + 1)

def checkUserInOrganization(conn: Optional[Connection], user: UserInfos):
    email = 'vbalamurugan@illumina.com'
    return True if __isReportTo(user, conn, email) else f'You are not reported to {email}. Not authorize to use this page.'

# Login Process
user = auth.login(checkUserInOrganization)
if user is not None:
    auth.createLogoutForm({'message':f"Welcome {user['displayName']}"})

    # Your page application can be written below
    st.write("# Welcome to my App! 👋")
    st.write(user)

Now run it to open the app!

streamlit run report_login.py

Additional check against list of users after ldap authentication completed

Create a new file list_login.py with the following code:

import streamlit as st
from streamlit_ldap_authenticator import Authenticate, Connection, UserInfos
from typing import Optional

# Declare the authentication object
auth = Authenticate(
    st.secrets['ldap'],
    st.secrets['session_state_names'],
    st.secrets['auth_cookie']
)

def checkUserInList(conn: Optional[Connection], user: UserInfos):
    allowUsers = [ "nchen1@illumina.com" ]
    if user['userPrincipalName'] in allowUsers: return True
    return f"You are not in the authorized list. Not allowed to use this page"

# Login Process
user = auth.login(checkUserInList)
if user is not None:
    auth.createLogoutForm({'message':f"Welcome {user['displayName']}"})

    # Your page application can be written below
    st.write("# Welcome to my App! 👋")
    st.write(user)

Now run it to open the app!

streamlit run list_login.py

Change Log

Version 0.0.4

  • Initial release

Version 0.0.5

  • default use_ssl for ldap connection to True
  • Added use_ssl configuration in LdapConfig

Version 0.0.6

  • fix page application not working when auto renewal for cookie config is configured.

Version 0.1.0

  • Add encryption module
  • Change user interface
  • More customizable form config
  • Remove LoginFormConfig and LogoutFormConfig

Version 0.1.1

  • Add pyjwt in the install requirement

Version 0.2.0

  • Add callback argument in login and logout

Version 0.2.1

  • Fix cannot login if encryptor module is provided.
  • Fix cookie auto renewal not working when no additionalCheck parameter is provided.

Version 0.2.2

  • Fix misleading error message of "Wrong username or password" when there is an exception occured during ldap connection

Version 0.2.3

  • Enhance security by clearing password from Connection object after bind.

Version 0.2.4

  • Fix 'no attribute in signinevent' when cookie option is disabled.

Version 0.2.5

  • Add Optional delay_sec in cookie config for set and del cookie.

Version 0.2.6

  • Fix expiry_days and delay_sec is not parse correctly from secrets.toml in CookieConfig.

FAQs


Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc