FastAPI Security Authentication
FastAPI has built-in security tools supporting common authentication and authorization methods such as OAuth2, JWT tokens, and API Keys. This section introduces how to implement user authentication based on OAuth2 + JWT.
Overview of security authentication
Security schemes supported by FastAPI:
| Solution | Applicable scenarios | Description |
|---|---|---|
| HTTP Basic Auth | Simple internal services | Username and password encoded in the request header, lower security |
| API Key | Service-to-service calls | Pass the key via request header, query parameter, or Cookie |
| OAuth2 + JWT | Front-end/back-end separated applications | The most commonly used scheme, secure and flexible |
OAuth2 password flow + JWT
This is the most commonly used authentication scheme in front-end/back-end separated applications. Flow:
- The client sends the username and password to
/tokenEndpoint - The server verifies the credentials and returns a JWT access token
- The client includes the token in subsequent requests (
Authorization: Bearer) - The server verifies the token and identifies the user
1. Install dependencies
pip install "python-jose[cryptography]" passlib[bcrypt]
2. Complete example
Example
from
datetime
import
datetime
,
timedelta
from
typing
import
Annotated
from
fastapi
import
Depends
,
FastAPI
,
HTTPException
,
status
from
fastapi.
security
import
OAuth2PasswordBearer
,
OAuth2PasswordRequestForm
from
jose
import
JWTError
,
jwt
from
passlib.
context
import
CryptContext
from
pydantic
import
BaseModel
===== Configuration =====
SECRET_KEY
=
"your-secret-key-keep-it-secret"
Use environment variables in production
ALGORITHM
=
"HS256"
ACCESS_TOKEN_EXPIRE_MINUTES
=
30
===== Password hashing =====
pwd_context
=
CryptContext
(
schemes
=
[
"bcrypt"
]
,
deprecated
=
"auto"
)
===== OAuth2 scheme =====
oauth2_scheme
=
OAuth2PasswordBearer
(
tokenUrl
=
"token"
)
===== Data models =====
class
Token
(
BaseModel
)
:
access_token:
str
token_type:
str
class
TokenData
(
BaseModel
)
:
username:
str
|
None
=
None
class
User
(
BaseModel
)
:
username:
str
:
str
|
None
=
None
full_name:
str
|
None
=
None
disabled:
bool
|
None
=
None
class
UserInDB
(
User
)
:
hashed_password:
str
===== Mock database =====
fake_users_db
=
{
"alice"
:
{
"username"
:
"alice"
,
"full_name"
:
"Alice Wonderson"
,
"email"
:
"alice@example.com"
,
"hashed_password"
: pwd_context.
hash
(
"secret"
)
,
Password: secret
"disabled"
:
False
,
}
}
===== Utility functions =====
def
verify_password
(
plain_password:
str
,
hashed_password:
str
)
bool
:
"""Verify password"""
return
pwd_context.
verify
(
plain_password
,
hashed_password
)
def
get_password_hash
(
password:
str
)
str
:
"""Generate password hash"""
return
pwd_context.
hash
(
password
)
def
get_user
(
db:
dict
,
username:
str
)
UserInDB |
None
:
"""Get user from database"""
if
username
in
db:
return
UserInDB
(
**db
[
username
]
)
return
None
def
authenticate_user
(
db:
dict
,
username:
str
,
password:
str
)
:
"""Verify user credentials"""
user
=
get_user
(
db
,
username
)
if
not
user
:
return
False
if
not
verify_password
(
password
,
user
.
hashed_password
)
:
return
False
return
user
def
create_access_token
(
data:
dict
,
expires_delta: timedelta |
None
=
None
)
:
"""Create JWT access token"""
to_encode
=
data.
copy
(
)
expire
=
datetime
.
utcnow
(
)
(
expires_delta
or
timedelta
(
minutes
=
15
)
)
to_encode.
update
(
{
"exp"
: expire
}
)
return
jwt.
encode
(
to_encode
,
SECRET_KEY
,
algorithm
=
ALGORITHM
)
async
def
get_current_user
(
token
: Annotated
[
str
,
Depends
(
oauth2_scheme
)
]
)
:
"""Get the current user from the token (dependency function)"""
credentials_exception
=
HTTPException
(
status_code
=
status.
HTTP_401_UNAUTHORIZED
,
detail
=
"Could not validate credentials"
,
headers
=
{
"WWW-Authenticate"
:
"Bearer"
}
,
)
try
:
payload
=
jwt.
decode
(
token
,
SECRET_KEY
,
algorithms
=
[
ALGORITHM
]
)
username:
str
=
payload.
get
(
"sub"
)
if
username
is
None
:
raise
credentials_exception
except
JWTError:
raise
credentials_exception
user
=
get_user
(
fake_users_db
,
username
)
if
user
is
None
:
raise
credentials_exception
return
user
async
def
get_current_active_user
(
current_user: Annotated
[
User
,
Depends
(
get_current_user
)
]
,
)
:
"""Get the current active user"""
if
current_user.
disabled
:
raise
HTTPException
(
status_code
=
400
,
detail
=
"User is inactive"
)
return
current_user
===== Routes =====
app
=
FastAPI
(
)
@
app.
post
(
"/token"
)
async
def
login
(
form_data: Annotated
[
OAuth2PasswordRequestForm
,
Depends
(
)
]
)
:
"""Log in to get a token"""
user
=
authenticate_user
(
fake_users_db
,
form_data.
username
,
form_data.
password
)
if
not
user
:
raise
HTTPException
(
status_code
=
status.
HTTP_401_UNAUTHORIZED
,
detail
=
"Incorrect username or password"
,
headers
=
{
"WWW-Authenticate"
:
"Bearer"
}
,
)
access_token_expires
=
timedelta
(
minutes
=
ACCESS_TOKEN_EXPIRE_MINUTES
)
access_token
=
create_access_token
(
data
=
{
"sub"
:
user
.
username
}
,
expires_delta
=
access_token_expires
)
return
{
"access_token"
: access_token
,
"token_type"
:
"bearer"
}
@
app.
get
(
"/users/me"
)
async
def
read_users_me
(
current_user: Annotated
[
User
,
Depends
(
get_current_active_user
)
]
,
)
:
"""Get current user information (authentication required)"""
return
current_user
@
app.
get
(
"/users/me/items"
)
async
def
read_own_items
(
current_user: Annotated
[
User
,
Depends
(
get_current_active_user
)
]
,
)
:
"""Get the current user's items (authentication required)"""
return
[
{
"item_id"
:
"Foo"
,
"owner"
: current_user.
username
}
]
Code Analysis
Password hashing
Use passlib 's bcrypt algorithm hashes passwords, ensuring that no plaintext passwords are stored in the database:
| function | Description |
|---|---|
pwd_context.hash(password) |
Convert a plaintext password to a hash value |
pwd_context.verify(plain, hashed) |
Verify whether a plaintext password matches the hash value |
JWT Tokens
JWT (JSON Web Token) is a secure token format that contains user information and an expiration time:
| Operation | function | Description |
|---|---|---|
| Create a token | jwt.encode() |
Encode data into a JWT string |
| Parse a token | jwt.decode() |
Parse and verify a JWT string |
| Set expiration | "exp": expire |
The token's expiration time |
| Store user identifier | "sub": username |
The subject of the token (usually the username) |
OAuth2PasswordBearer
Tell FastAPI to get the token from the Authorization: Bearer request header:
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
tokenUrl="token" Specifies the endpoint path where clients obtain the token, which appears in the API documentation.
SECRET_KEYMust be kept secret and sufficiently complex; in production it should be stored using environment variables. If the secret is leaked, an attacker can forge tokens for any user.
Test using the API documentation
After configuring OAuth2, an "Authorize" button appears in Swagger UI:
- Click "Authorize"
- Enter the username and password (e.g.
alice/secret) - Click "Authorize" Get token
- All subsequent requests will automatically carry the token
Summary
- OAuth2 + JWT is the most commonly used authentication scheme for front-end/back-end separated applications
- Passwords must be stored hashed, never in plaintext
- JWT tokens contain user identifiers and expiration times
- Use dependency injection (
Depends) to achieve reuse of authentication logic - In production, SECRET_KEY must be kept secret