On this page

FastAPI Password Hashing with Argon2 and pwdlib

Published on August 13, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Passwords should never be stored as plain, readable text in a database — if that database is ever exposed, every user's real password goes with it. The fix is hashing: converting each password into a one-way, irreversible string before it's saved, using Argon2 through the pwdlib library. Done correctly, a full database leak still can't be turned back into anyone's actual password, and a login system that verifies credentials through that same hashing process closes off the easiest ways an attacker could otherwise guess passwords or find out which accounts even exist.


Why Passwords Must Never Be Stored in Plaintext​

Storing a password as-is means a single database compromise — SQL injection, an exposed backup, a misconfigured access control — hands over every user's actual password at once, including on any other service where that same password was reused. Hashing replaces the password with a fixed-length, one-way digest before it's ever written to disk. The original password can't be recovered from that digest; verifying a login attempt means hashing the submitted password again and comparing the result to what's stored, never decrypting anything.


Why pwdlib and Argon2​

For years, passlib was the standard library for this in Python, but it's gone largely unmaintained and depends on the standard library's crypt module, which was removed starting in Python 3.13 — the library stops working outright on that version and later. pwdlib was built specifically to replace it, and it's the library FastAPI's own current documentation uses in its examples. PasswordHash.recommended() configures it with Argon2 by default, without needing the algorithm specified manually.

Argon2 itself is the right default for a new project for reasons specific to what password hashing needs. It won the Password Hashing Competition, a multi-year public evaluation specifically aimed at identifying the strongest general-purpose password hashing algorithm available. It's memory-hard as well as CPU-intensive, meaning an attacker attempting to brute-force it at scale needs meaningful memory per guess, not just processing time — this is what makes GPU-based cracking, which parallelizes cheap, memory-light computations extremely well, far less effective against Argon2 than against older algorithms. And it salts every hash automatically, so two users who happen to choose the same password end up with completely different stored values, which defeats precomputed rainbow-table attacks outright.


Installing pwdlib​


pip install "pwdlib[argon2]"

The [argon2] extra installs the actual Argon2 implementation pwdlib wraps — without it, PasswordHash.recommended() has no working hasher to configure.


Building the Hashing Utility​

app/core/security.py:


from pwdlib import PasswordHash



password_hash = PasswordHash.recommended()



def get_password_hash(password: str) -> str:

    """Converts a plain-text password into a salted Argon2id hash string."""

    return password_hash.hash(password)



def verify_password(plain_password: str, hashed_password: str) -> bool:

    """Checks a login attempt's password against the stored hash."""

    return password_hash.verify(plain_password, hashed_password)

PasswordHash.recommended() selects Argon2 with its current recommended parameters, and those parameters are free to improve in a future pwdlib release without any code here needing to change. password_hash.verify() takes the plain-text password first and the stored hash second — getting this order backwards is a common mistake worth double-checking, since both arguments are plain strings and a swapped call won't raise an error, it will just always evaluate incorrectly.


Hashing Passwords at Signup​

app/routers/auth.py:


from fastapi import APIRouter, HTTPException, status

from pydantic import BaseModel, EmailStr, Field

from app.core.security import get_password_hash



router = APIRouter(tags=["Authentication"])



fake_user_db = {}



class UserRegisterSchema(BaseModel):

    email: EmailStr

    password: str = Field(..., min_length=8, description="Password must be at least 8 characters.")



@router.post("/signup", status_code=status.HTTP_201_CREATED)

async def register_user(user_data: UserRegisterSchema):

    if user_data.email in fake_user_db:

        raise HTTPException(

            status_code=status.HTTP_400_BAD_REQUEST,

            detail="An account with this email already exists.",

        )



    hashed_password = get_password_hash(user_data.password)



    fake_user_db[user_data.email] = {

        "email": user_data.email,

        "hashed_password": hashed_password,

    }

    return {"message": "User registered successfully!", "email": user_data.email}

Field(..., min_length=8, ...) rejects a password shorter than eight characters before the handler body ever runs — Pydantic validates it as part of parsing the request. get_password_hash(user_data.password) is the one line where the plaintext password gets converted into its Argon2 hash; everything stored in fake_user_db afterward is that hash, and the plaintext value is never written anywhere.


Verifying Passwords at Login​

app/routers/auth.py (continued):


from fastapi import Depends

from app.core.security import verify_password, password_hash



# Computed once at startup, reused for every login attempt on a missing user

DUMMY_HASH = password_hash.hash("dummypassword")



class LoginSchema(BaseModel):

    email: EmailStr

    password: str



@router.post("/login")

async def login_user(credentials: LoginSchema):

    user = fake_user_db.get(credentials.email)



    if not user:

        # Run a real verification anyway, so a missing user takes

        # the same amount of time as a wrong password

        verify_password(credentials.password, DUMMY_HASH)

        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect email or password.")



    is_valid = verify_password(credentials.password, user["hashed_password"])

    if not is_valid:

        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect email or password.")



    return {"message": "Authentication successful!", "token_type": "bearer"}

Without the dummy verification call, a request for a nonexistent email would return its 401 almost instantly — no hash to check against — while a request with a real email and a wrong password would take measurably longer, since Argon2 verification actually has to run. That timing difference is enough for an attacker to enumerate which email addresses have accounts, one timed request at a time, without ever seeing a password. Running verify_password against a precomputed dummy hash even when no user exists keeps both code paths taking roughly the same amount of time, closing that gap. DUMMY_HASH is computed once when the module loads, not on every request — hashing it fresh each time would defeat the purpose by adding real, variable-length work to the very case being protected against.


Keeping the Event Loop Responsive​

Argon2 verification is deliberately CPU-intensive, and login_user above is declared async def. This combination matters more than it might look: FastAPI automatically runs a def-declared route handler in a thread pool on its own, but that automatic behavior applies to the route function as a whole — it does not apply to an ordinary blocking function called from inside an async def route. Calling verify_password directly inside login_user runs that CPU-bound work on the same event loop handling every other concurrent request, and a busy login endpoint can measurably slow down unrelated requests while Argon2 is churning.

fastapi.concurrency.run_in_threadpool moves that specific call off the event loop and onto a worker thread instead:


from fastapi.concurrency import run_in_threadpool



is_valid = await run_in_threadpool(verify_password, credentials.password, user["hashed_password"])

This one change is what keeps a spike in login attempts from degrading response times on every other endpoint the application serves at the same time.


Migrating Legacy Password Hashes​

pwdlib can be configured with more than one hasher at once, which makes it possible to keep verifying passwords stored under an older algorithm while new hashes use Argon2:


from pwdlib import PasswordHash

from pwdlib.hashers.argon2 import Argon2Hasher

from pwdlib.hashers.bcrypt import BcryptHasher



# The first hasher listed is used for new hashes;

# older ones are still accepted for verification

password_hash = PasswordHash((Argon2Hasher(), BcryptHasher()))



valid, updated_hash = password_hash.verify_and_update(plain_password, stored_hash)

if valid and updated_hash:

    # The password was correct, but the hash was on an older algorithm —

    # save updated_hash back to the database to complete the migration for this user

    save_new_hash(user_id, updated_hash)

verify_and_update checks the submitted password against whichever hasher actually produced the stored hash, and returns a new Argon2 hash only if the check succeeds and the stored hash was using an outdated algorithm — nothing is generated or saved if the password was wrong. This lets an existing user base migrate onto Argon2 gradually, one successful login at a time, with no forced password reset for anyone.


Key Takeaways​

Hashing turns a stored password into something a database breach can't turn back into the original credential, and Argon2 is the right algorithm for that specifically because it's memory-hard, salted automatically, and was selected through open competition rather than convention. pwdlib provides that through PasswordHash.recommended() where passlib no longer reliably works. Verifying a login attempt through the same deliberately slow comparison — including a dummy check on a missing user, so that lookup timing doesn't leak which accounts exist — closes the gap between "the password is technically hashed" and "the system is actually resistant to enumeration and brute-force attacks." Because that verification is CPU-heavy, an async def login route needs run_in_threadpool around it specifically, since FastAPI's automatic thread-pool handling only covers the route function as a whole, not a blocking call made from inside an already-async one.


Practice: Strengthening Signup Validation​

Extending UserRegisterSchema to require at least one uppercase letter and one digit, using Pydantic's field_validator:


from pydantic import BaseModel, EmailStr, Field, field_validator



class UserRegisterSchema(BaseModel):

    email: EmailStr

    password: str = Field(..., min_length=8)



    @field_validator("password")

    @classmethod

    def password_must_be_strong(cls, value: str) -> str:

        if not any(char.isupper() for char in value):

            raise ValueError("Password must contain at least one uppercase letter.")

        if not any(char.isdigit() for char in value):

            raise ValueError("Password must contain at least one number.")

        return value

field_validator("password") runs after the built-in min_length=8 check already passes, and raising ValueError inside it produces the same structured 422 validation response FastAPI generates for any other failed field, with the specific message included in detail. Sending {"email": "[email protected]", "password": "weakpass"} to /signup now fails with a message about the missing uppercase letter, while {"email": "[email protected]", "password": "Strong1pass"} passes and reaches register_user.

Adding a single print(hashed_password) line inside register_user, right after calling get_password_hash, and watching the running server's terminal while sending a signup request through /docs shows the actual transformation directly: a readable password like "Strong1pass" becomes an Argon2 string starting with $argon2id$, followed by its parameters and a long block of encoded, unreadable characters — visibly nothing like the original input, and with no way to work backward from it.

Frequently Asked Questions​

Why does password_hash.verify() always return False even though the password looks correct?

The most common cause is the arguments being passed in the wrong order. verify() expects the plain-text password first and the stored hash second — password_hash.verify(plain_password, hashed_password). Swapping them doesn't raise an error, it just evaluates incorrectly every time, since both arguments are ordinary strings.

Why is get_password_hash() so slow compared to a normal function call?

This is expected and intentional. Argon2 is deliberately CPU- and memory-intensive, since that same slowness is what makes brute-forcing a stolen hash database impractical at scale. A hashing or verification call taking noticeably longer than a typical function call is a sign the algorithm is working correctly, not a performance bug to fix.

Do I need to store the salt separately alongside the hash?

No. pwdlib generates a random salt automatically and embeds it directly inside the returned hash string. The full string returned by password_hash.hash() is everything verify() needs later — no separate salt column or extra storage is required.

Why use a dummy hash check for a login attempt on an email that doesn't exist?

Without it, looking up a missing email returns almost instantly, while a real email with a wrong password takes measurably longer because an actual Argon2 verification runs. That timing difference lets an attacker determine which email addresses have accounts just by timing responses. Running verify_password() against a precomputed dummy hash even when no user is found keeps both cases taking roughly the same amount of time.

Why compute DUMMY_HASH once at the top of the file instead of inside the login function?

Hashing it fresh on every request would add real, variable-length work to the exact code path being protected, working against the timing consistency the dummy check exists to provide. Computing it once when the module loads means every login attempt on a missing user reuses the same precomputed hash.

My app installs fine but fails with an error about no available hasher. What's wrong?

This usually means pwdlib was installed without the algorithm extra — pip install pwdlib alone doesn't include the Argon2 implementation. Installing pip install "pwdlib[argon2]" (with the quotes, since some shells interpret unquoted square brackets as a wildcard) pulls in the actual hasher PasswordHash.recommended() needs.

Do I need run_in_threadpool if my route handler is defined with def instead of async def?

No. FastAPI already runs an entire def-declared route handler in a thread pool automatically. run_in_threadpool only matters for a blocking, CPU-heavy call made from inside an async def route, where that automatic thread-pool handling doesn't apply to the individual call.

What does verify_and_update() return if the password is correct and already using the current algorithm?

It returns (True, None) — the boolean confirms the password matched, and None means no update was necessary, since the hash was already using the current algorithm. A non-None second value is what specifically signals that the returned hash should be saved back to the database to complete a migration for that user.

My custom field_validator error isn't showing up in the 422 response. Why?

Check that the decorator order is @field_validator("password") directly above @classmethod, and that the function actually raises ValueError rather than returning False or printing a message. Pydantic only converts a raised ValueError into a structured validation error; a validator that merely returns a falsy value without raising is silently treated as passing.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Signup and Login Endpoints

Next

JWT Authentication