Passing Credentials to Deployed Streamlit Apps using Streamlit Secrets

behordeun

MUHAMMAD ABIODUN SULAIMAN

Posted on November 5, 2022

Passing Credentials to Deployed Streamlit Apps using Streamlit Secrets

Often as programmers, we get to deal with credentials, for instance, when we need to connect to a database or ingest data from sources besides our local computers. Hence, it becomes imperative to find a way to securely pass the credentials such that they are not exposed in our code scripts.

In this short article, I will explain how I used #StreamlitSecrets to resolve a problem with passing credentials to a #MachineLearning system I deployed to the web using #Streamlit. Before fixing the problem, the deployed app worked fine on my local computer while testing it because the credentials were passed to the ingestion pipeline using an environment variable file (.env); however, upon deploying to the web, the system failed to work due to unavailability of the credentials. Some steps in solving this problem include removing the environment variable file from gitignoreand creating a Python (.py) file; since the programming language I was working with was Python. Upon taking these steps, I could not push the local repository to the remote repository as pre-commit hook detected that credentials had been exposed and did not allow the push. Hence, I finally had to use the #StreamlitSecrets file (secrets.toml) to pass the credentials while updating the credentials on the app settings section of the deployed streamlit app. The steps taken to achieve this are listed below:

  1. Create the directory .streamlit/
  2. Create the secret file secrets.toml
  3. In the created secret file, type in the credentials in the below format:
[db_credentials]
user = 'someuser'
password = 'somepassword'
host = 'somehost'
database = 'somedatabase'
Enter fullscreen mode Exit fullscreen mode

PS: You can include other credentials as needed.

  1. In the python file, pass in the credentials with the following lines of code:
host=st.secrets.db_credentials.host,
user=st.secrets.db_credentials.user,
password=st.secrets.db_credentials.password,
db=st.secrets.db_credentials.database
Enter fullscreen mode Exit fullscreen mode
  1. Navigate to the url link of the deployed app, open settings, and type in the provided credentials in .streamlit/secrets.toml

Image description

The above steps ensure that your streamlit app works seamlessly on your local computer and the Streamlit deployed version.

If you find the article helpful, kindly click the like button and comment.

You can follow me on LinkedIn and Twitter for more updates.

πŸ’– πŸ’ͺ πŸ™… 🚩
behordeun
MUHAMMAD ABIODUN SULAIMAN

Posted on November 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related