- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Authentication, Authorization and Security
- OAuth2 & JWT
- Signup and Login Endpoints
On this page
FastAPI User Registration and Login Guide
Published on August 11, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A FastAPI signup and login system is only as secure as its weakest link: passwords must never touch the database in plaintext, and login must never confirm which part of a credential pair was wrong. Hashing every password with Argon2 through pwdlib before storage, and verifying login attempts through FastAPI's OAuth2 Password Flow with a single, undifferentiated error on failure, closes both gaps at once — the result is a signup endpoint that stores only irreversible hashes and a login endpoint that authenticates real users without leaking which usernames exist in the system.
Why Authentication Matters​
Authentication answers one specific question: who is this user, and can they prove it? Any API handling user-specific data or protected actions needs a way to establish that identity, and a secure system does it in a consistent shape — users register with a unique identity at signup, prove that identity with credentials at login, have their passwords stored as one-way hashes rather than plaintext, and receive a token once verified to present on later requests.
None of this is optional in a production system. A breach that exposes plaintext passwords compromises every affected user immediately, including on other services where the same password was likely reused. A breach that exposes properly hashed passwords is far less damaging, since a strong hash can't be reversed back into the original password.
What OAuth2 Is​
OAuth2 is an authorization framework defined in RFC 6749, describing a family of flows for how clients — browsers, mobile apps, CLI tools — obtain access tokens from an authorization server and later present those tokens to prove identity on protected resources. Two concepts commonly get conflated here and deserve separating clearly: authentication is verifying who a user is, covered in full below, while authorization is deciding what a verified user is allowed to do, typically handled later through scopes and roles. OAuth2 itself was designed primarily around authorization, but its Password Flow is commonly used for authentication specifically in first-party applications, where an application's own frontend talks directly to its own backend.
The OAuth2 Password Flow​
The Password Flow is the simplest OAuth2 grant type, and it's the one FastAPI's built-in security utilities are built around. A client sends a username and password to a login endpoint as application/x-www-form-urlencoded data — not JSON. The server looks up the user and verifies the submitted password against the stored hash. If the credentials check out, the server returns an access token, and the client attaches that token to every subsequent request to a protected route through an Authorization: Bearer <token> header. This flow has to run over HTTPS in production without exception — sending credentials over plain HTTP exposes them to interception in transit.
Understanding x-www-form-urlencoded​
The OAuth2 specification requires a login endpoint to receive credentials as application/x-www-form-urlencoded data — the same encoding standard HTML forms use. The request body looks like plain text: username=john&password=secret123, structurally different from a JSON body. FastAPI's OAuth2PasswordRequestForm parses this format automatically, giving a route handler direct access to form_data.username and form_data.password. It depends on the python-multipart library to do that parsing — without it installed, calling an endpoint that depends on OAuth2PasswordRequestForm fails with an explicit error stating that form parsing requires it:
pip install python-multipart
Defining the User Model​
models/user.py:
from sqlmodel import SQLModel, Field
from typing import Optional
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
username: str = Field(index=True, unique=True)
email: str
hashed_password: str
is_active: bool = True
Why this structure​
username is the credential used at login; unique=True generates a database-level UNIQUE index on this column, enforcing uniqueness beyond whatever the application checks on its own. email is stored for account recovery or contact purposes, not used for login in this implementation. hashed_password stores only the Argon2 hash of the password — even with full read access to the database, the original password can't be recovered from this value. is_active is a soft-disable flag, letting an account be deactivated without deleting its record or anything associated with it, which is the standard approach to account suspension.
Hashing Passwords with pwdlib​
passlib, the library still widely referenced in older FastAPI material, has gone largely unmaintained and depends on the standard library's crypt module, which was removed starting Python 3.13 — the library's own maintainers confirm it stops working on that version and later. FastAPI's own official documentation has since moved to pwdlib in its place — a modern, actively maintained library where PasswordHash.recommended() defaults to Argon2, currently the strongest widely recommended password hashing algorithm and the winner of the Password Hashing Competition. pwdlib also supports bcrypt, but Argon2 is the correct default for a new project.
pip install 'pwdlib[argon2]'
core/security.py:
from pwdlib import PasswordHash
password_hash = PasswordHash.recommended()
def hash_password(password: str) -> str:
return password_hash.hash(password)
def verify_password(plain: str, hashed: str) -> bool:
return password_hash.verify(plain, hashed)
Why Argon2, and why hash at all​
Storing passwords in plaintext is indefensible — a database compromise through SQL injection, a misconfigured backup, or exposed server access immediately exposes every user's actual password. Hashing turns a password into a fixed-length, irreversible digest; the original can't be recovered from it, and verifying a login attempt means hashing the submitted password fresh and comparing the result to the stored hash.
Argon2 fits this purpose for three specific reasons. It's intentionally slow and memory-hard, requiring meaningful memory as well as CPU time, which makes brute-force attacks — GPU-based ones especially — impractical even against an attacker holding the full hash database. It incorporates a random salt automatically into every hash, so two users sharing the same password end up with entirely different stored hashes, defeating precomputed rainbow-table attacks outright. And PasswordHash.recommended() tracks current best-practice defaults, meaning an application benefits from future parameter updates without any code changes at all.
General-purpose hash functions — MD5, SHA-1, SHA-256, SHA-512 — are the wrong tool here specifically because they're designed to be fast, which is the opposite of what a credential hash needs; a modern GPU computes billions of SHA-256 hashes per second.
The Signup Endpoint​
routers/auth.py:
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session, select
from models.user import User
from db import get_session
from core.security import hash_password
router = APIRouter(prefix="/auth", tags=["Auth"])
@router.post("/signup", status_code=201)
def signup(user: User, session: Session = Depends(get_session)):
existing_user = session.exec(
select(User).where(User.username == user.username)
).first()
if existing_user:
raise HTTPException(status_code=400, detail="Username already exists")
user.hashed_password = hash_password(user.hashed_password)
session.add(user)
session.commit()
session.refresh(user)
return {"message": "User created", "user_id": user.id}
What's happening​
The endpoint checks for an existing user with the same username before inserting, producing a clear 400 Bad Request with a readable message at the application level. The unique=True constraint on the model provides a second layer of protection at the database level — if two concurrent requests somehow race past the application-level check at the same moment, the database itself rejects whichever insert arrives second. hash_password(user.hashed_password) passes the raw submitted password through Argon2 and overwrites hashed_password on the object before it's committed — after this line runs, only the hash exists anywhere in memory or in the database, with the plaintext value gone. session.refresh(user) reloads the row after commit, populating id with the value the database's auto-increment assigned.
Example request body:
POST /auth/signup
{
"username": "john",
"email": "[email protected]",
"hashed_password": "plaintextpassword"
}
A known design limitation​
The signup endpoint here uses the User table model directly as the request body, which means a client sends a raw plaintext password in a field literally named hashed_password. That naming is confusing by design — the field stores a hash once it reaches the database, but what the client actually sends is plaintext. A dedicated UserCreate Pydantic schema with a properly named password field, kept cleanly separate from the User table model, resolves this and belongs at a later stage once request and table schemas are separated more generally.
The Login Endpoint with OAuth2​
routers/auth.py (continued):
from fastapi.security import OAuth2PasswordRequestForm
from core.security import verify_password
@router.post("/login")
def login(
form_data: OAuth2PasswordRequestForm = Depends(),
session: Session = Depends(get_session),
):
user = session.exec(
select(User).where(User.username == form_data.username)
).first()
if not user or not verify_password(form_data.password, user.hashed_password):
raise HTTPException(status_code=401, detail="Invalid credentials")
return {"message": "Login successful", "user_id": user.id}
What's happening​
form_data: OAuth2PasswordRequestForm = Depends() tells FastAPI to parse the request body as application/x-www-form-urlencoded and populate form_data.username and form_data.password — the standard OAuth2 credential format, not JSON. The user is looked up by username; if none is found, or verify_password returns False, a 401 Unauthorized is raised. The two distinct failure cases — an unknown username and a correct username with the wrong password — are deliberately collapsed into the exact same error message, since distinguishing them would let an attacker enumerate which usernames actually exist in the system by watching which error comes back. verify_password calling password_hash.verify(plain, hashed) from pwdlib is intentionally slow — every login attempt taking a small, measurable amount of time is expected and correct behavior, since that same slowness is what makes offline brute-force attacks against a stolen hash database expensive.
An intentionally incomplete step​
A fully OAuth2-compliant token endpoint returns {"access_token": "...", "token_type": "bearer"} and includes a WWW-Authenticate: Bearer header on 401 responses. The endpoint above returns a plain success message in place of an actual token — both the token response and that header get added once JWT generation is introduced as the next piece of this authentication system.
Checking is_active​
The login endpoint above never checks user.is_active, which means a deactivated account can still authenticate successfully. Production authentication logic needs to reject inactive accounts explicitly:
if not user or not verify_password(form_data.password, user.hashed_password):
raise HTTPException(status_code=401, detail="Invalid credentials")
if not user.is_active:
raise HTTPException(status_code=403, detail="Account is disabled")
The inactive-account response uses 403 Forbidden, not 401 Unauthorized, deliberately: a 401 means the credentials themselves aren't recognized, while a 403 means the credentials were valid but access is denied anyway — the correct semantic when a known, verified user has been suspended. A client can use that distinction to show genuinely different messages for "wrong password" versus "account disabled."
Testing in Swagger UI​
Visiting /docs allows testing both endpoints interactively: POST /auth/signup takes a JSON body with username, email, and hashed_password, while POST /auth/login takes the form fields username and password — FastAPI renders OAuth2PasswordRequestForm as an actual form in Swagger UI, distinct from the JSON body editor used everywhere else, and the login endpoint specifically cannot be tested with a JSON body at all. Testing with curl or Postman requires the form-data option — -F in curl — rather than a JSON body passed with -d.
Required Dependencies​
PackagePurposeInstallpwdlib[argon2]Argon2 password hashing and verificationpip install 'pwdlib[argon2]'``python-multipartParses x-www-form-urlencoded form datapip install python-multipart
Both need to be installed for the endpoints above to function at all.
Key Takeaways​
POST /auth/signup and POST /auth/login together establish the full authentication foundation: a User model with a username uniqueness constraint enforced at both the application and database level, Argon2 password hashing through pwdlib's PasswordHash.recommended() for best-practice defaults that improve automatically over time, and credential verification through verify_password — a deliberately slow, Argon2-aware comparison rather than a fast general-purpose hash. Both endpoints carry an honest limitation worth remembering as this system develops further: signup exposes its password field with a confusing name that a dedicated request schema resolves later, and login currently returns a plain success message rather than the access token and WWW-Authenticate header a fully OAuth2-compliant flow requires — both addressed directly once JWT issuance is introduced.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
OAuth2 & JWT
Next
Password Hashing
-
Why Authentication Matters
-
What OAuth2 Is
-
The OAuth2 Password Flow
-
Understanding x-www-form-urlencoded
-
Defining the User Model
- Why this structure
-
Hashing Passwords with pwdlib
- Why Argon2, and why hash at all
-
The Signup Endpoint
- What's happening
- A known design limitation
-
The Login Endpoint with OAuth2
- What's happening
- An intentionally incomplete step
-
Checking is_active
-
Testing in Swagger UI
-
Required Dependencies
-
Key Takeaways
