Skip to main content
Earlier, we outlined the process for creating a new user. However, storing passwords as plain text poses a significant security risk. Even if your database is secure now, a breach could expose these passwords to attackers. Instead, always store a hashed version of the password. Hashing is a one-way process that makes it practically impossible to retrieve the original password from its hash. For instance, running the following SQL command:
reveals that storing plain text passwords (as the query would show) is unsafe. Always hash passwords before saving them to your database.
FastAPI’s documentation provides an excellent guide on password hashing under the OAuth2 with Password section.

Installing Required Libraries

To implement password hashing, you need two libraries: Passlib (which supports multiple hashing algorithms) and bcrypt (the algorithm we will use). Install them using pip:
Alternatively, install both libraries directly:
After installation, verify that both libraries are installed by running pip freeze.

Application Models and Environment

Below is a snippet from our application models and configurations:
And a sample of our environment package list:

Configuring the Password Hasher

In your main file, import CryptContext from Passlib to create a password context that utilizes bcrypt:
This configuration sets up the CryptContext to use the bcrypt algorithm for secure password hashing.

Updating the User Registration Endpoint

To ensure passwords are securely stored, update the registration endpoint to hash the password before saving it to the database:
A similar version of this endpoint appears as follows:
After creating a user, you can confirm that the password has been hashed by running:
Since hashing is a one-way process, retrieving the original password from the hash is not feasible.

Extracting the Hashing Logic for Maintainability

To improve code maintainability, extract the password hashing logic into a separate utility function. Create a new file named utils.py with the following content:
Then, modify your main.py to import and use this new utility function:
Update the user registration endpoint to use the utility function for hashing:
After testing the endpoint—by creating a new user (e.g., email “mark@gmail.com” with password “password123”)—query the users table:
This query will confirm that the application stores only the hashed password, significantly reducing security risks in the event of a data breach.
By following these steps, you enhance your application’s security by ensuring user passwords are hashed rather than stored in plain text. This practice is essential for maintaining user data integrity.

Watch Video