Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

User System — Registration, Login, JWT Authentication

User System — Registration, Login, JWT Authentication

In this chapter you'll learn FastAPI's JWT authentication scheme and understand how it differs from Django/Flask Session authentication.


JWT vs Session authentication

Django and Flask use Session authentication: the server stores user state, and the cookie only stores the Session ID.

FastAPI recommends JWT authentication: after login, the user gets a token, and subsequent requests carry the token for authentication.

Feature Session(Django/Flask) JWT(FastAPI)
Storage location Server-side (memory/database) Client-side (Cookie/LocalStorage)
Extensibility Servers must share the Session Stateless, naturally supports distributed systems
Applicable scenarios Server-rendered websites API + SPA / mobile
Expiration control Can be invalidated by the server at any time Remains valid until the token expires

Install dependencies



(venv) $ pip install passlib python-jose python-multipart


Define the User model

Example

File path: add to models.py

from

passlib.

context

import

CryptContext

pwd_context

=

CryptContext

(

schemes

=

[

"bcrypt"

]

,

deprecated

=

"auto"

)

class

User

(

Base

)

:

    tablename

=

"users"

   

id

=

Column

(

Integer

,

primary_key

=

True

,

index

=

True

)

    username

=

Column

(

String

(

50

)

,

unique

=

True

,

nullable

=

False

)

   

email

=

Column

(

String

(

120

)

,

unique

=

True

,

nullable

=

False

)

    hashed_password

=

Column

(

String

(

256

)

,

nullable

=

False

)

   

def

set_password

(

self

,

password:

str

)

:

       

"""Hash password"""

       

self

.

hashed_password

=

pwd_context.

hash

(

password

)

   

def

verify_password

(

self

,

password:

str

)

bool

:

       

"""Verify password"""

       

return

pwd_context.

verify

(

password

,

self

.

hashed_password

)

Generate and run the migration:



(venv) $ alembic revision --autogenerate -m "新增 User 模型"

(venv) $ alembic upgrade head


JWT utility functions

Example

File path: auth.py (new file)

from

datetime

import

datetime

,

timedelta

from

jose

import

JWTError

,

jwt

from

passlib.

context

import

CryptContext

from

fastapi

import

Depends

,

HTTPException

,

status

from

fastapi.

security

import

OAuth2PasswordBearer

Secret key (read from an environment variable in production)

SECRET_KEY

=

"your-secret-key-change-in-production"

ALGORITHM

=

"HS256"

ACCESS_TOKEN_EXPIRE_MINUTES

=

60

24

 

Token validity: 24 hours

OAuth2PasswordBearer tells FastAPI: from the request header Authorization: Bearer extract the JWT

oauth2_scheme

=

OAuth2PasswordBearer

(

tokenUrl

=

"token"

)

def

create_access_token

(

data:

dict

)

str

:

   

"""Generate a JWT token"""

    to_encode

=

data.

copy

(

)

    expire

=

datetime

.

utcnow

(

)

(

minutes

=

ACCESS_TOKEN_EXPIRE_MINUTES

)

    to_encode.

update

(

{

"exp"

: expire

}

)

   

return

jwt.

encode

(

to_encode

,

SECRET_KEY

,

algorithm

=

ALGORITHM

)

def

decode_access_token

(

token

:

str

)

dict

|

None

:

   

"""Verify and decode a JWT token"""

   

try

:

        payload

=

jwt.

decode

(

token

,

SECRET_KEY

,

algorithms

=

[

ALGORITHM

]

)

       

return

payload

   

except

JWTError:

       

return

None


Registration route

Example

File path: routers/users.py

from

fastapi

import

APIRouter

,

Depends

,

HTTPException

,

Request

,

Form

from

fastapi.

templating

import

Jinja2Templates

from

sqlalchemy.

orm

import

Session

from

database

import

get_db

from

models

import

User

from

schemas

import

UserCreate

,

UserResponse

from

auth

import

create_access_token

router

=

APIRouter

(

prefix

=

"/users"

,

tags

=

[

"User"

]

)

templates

=

Jinja2Templates

(

directory

=

"templates"

)

@

router.

post

(

"/register"

,

response_model

=

UserResponse

)

def

register

(

    username:

str

=

Form

(

...

)

,

   

email

:

str

=

Form

(

...

)

,

    password:

str

=

Form

(

...

)

,

    db: Session

=

Depends

(

get_db

)

)

:

   

"""User registration"""

   

Check whether the username and email already exist

   

if

db.

query

(

User

)

.

filter

(

User.

username

==

username

)

.

first

(

)

:

       

raise

HTTPException

(

status_code

=

400

,

detail

=

"Username already in use"

)

   

if

db.

query

(

User

)

.

filter

(

User.

email

==

email

)

.

first

(

)

:

       

raise

HTTPException

(

status_code

=

400

,

detail

=

"Email already registered"

)

   

user

=

User

(

username

=

username

,

email

=

email

)

   

user

.

set_password

(

password

)

    db.

add

(

user

)

    db.

commit

(

)

    db.

refresh

(

user

)

   

return

user


Login route (issuing JWT)

Example

File path: append to routers/users.py

from

fastapi.

security

import

OAuth2PasswordRequestForm

from

auth

import

create_access_token

@

router.

post

(

"/token"

)

def

login_for_access_token

(

    form_data: OAuth2PasswordRequestForm

=

Depends

(

)

,

    db: Session

=

Depends

(

get_db

)

)

:

   

"""
    Log in and get a token
    Using OAuth2PasswordRequestForm: the fields are username and password (form format)
    """

   

user

=

db.

query

(

User

)

.

filter

(

User.

username

==

form_data.

username

)

.

first

(

)

   

if

not

user

or

not

user

.

verify_password

(

form_data.

password

)

:

       

raise

HTTPException

(

            status_code

=

401

,

            detail

=

"Incorrect username or password"

,

            headers

=

{

"WWW-Authenticate"

:

"Bearer"

}

       

)

   

Issue a JWT containing only user_id (no sensitive information)

    access_token

=

create_access_token

(

data

=

{

"sub"

:

str

(

user

.

id

)

}

)

   

return

{

"access_token"

: access_token

,

"token_type"

:

"bearer"

}

In the JWT token, sub is the standard subject field, storing the user identifier. The token itself is not encrypted (just Base64-encoded), soyou must neverput sensitive information like passwords in it. If you want encryption, use JWE instead of JWT.


Using JWT protection in routes

Example

Dependency function to get the current user

from

auth

import

oauth2_scheme

,

decode_access_token

def

get_current_user

(

   

token

:

str

=

Depends

(

oauth2_scheme

)

,

    db: Session

=

Depends

(

get_db

)

)

:

   

"""Parse the current user from the JWT token"""

    payload

=

decode_access_token

(

token

)

   

if

payload

is

None

:

       

raise

HTTPException

(

status_code

=

401

,

detail

=

"Token is invalid or expired"

)

    user_id

=

payload.

get

(

"sub"

)

   

user

=

db.

query

(

User

)

.

filter

(

User.

id

==

int

(

user_id

)

)

.

first

(

)

   

if

user

is

None

:

       

raise

HTTPException

(

status_code

=

401

,

detail

=

"User does not exist"

)

   

return

user

Inject into routes that require login

@

router.

get

(

"/me"

,

response_model

=

UserResponse

)

def

read_current_user

(

current_user: User

=

Depends

(

get_current_user

)

)

:

   

"""Get current user info (login required)"""

   

return

current_user

For SSR pages, JWTs are usually stored in a cookie (rather than the Authorization header), and the token is extracted from the cookie in template routes for verification.


Chapter Summary

In this chapter you implemented FastAPI's JWT authentication: passlib for hashing passwords, python-jose for issuing and verifying JWTs, OAuth2PasswordBearer for extracting tokens, and Depends for authentication dependency injection.

Unlike Django/Flask's Session authentication, JWT is a stateless scheme better suited to front-end/back-end separation.