DEV Community

Fiyinfoluwa Ojo
Fiyinfoluwa Ojo

Posted on

JWT Authentication: Securing API Routes with JSON Web Tokens in FastAPI

What is JWT?

A JSON Web Token (JWT) is a compact, self-contained
token that proves who you are. Instead of sending
your password with every request, you log in once,
get a token, and use that token for all future requests.

How It Works

  1. User sends email + password to /auth/login
  2. Server verifies credentials
  3. Server generates a JWT containing user ID
  4. User sends that JWT with every protected request
  5. Server verifies the token and grants access

Generating the Token

def create_token(user_id: int, email: str):
    payload = {
        "user_id": user_id,
        "email": email,
        "exp": datetime.utcnow() + timedelta(hours=24)
    }
    return jwt.encode(payload, SECRET_KEY, algorithm="HS256")
Enter fullscreen mode Exit fullscreen mode

The token contains user_id, email and an expiry time.
It's signed with a secret key, tamper with it and
it becomes invalid.

Verifying the Token

def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    token = credentials.credentials
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        return payload
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token has expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")
Enter fullscreen mode Exit fullscreen mode

The Protected Route

@app.get("/protected")
def protected_route(current_user: dict = Depends(verify_token)):
    return {
        "message": "You have access!",
        "user": current_user
    }
Enter fullscreen mode Exit fullscreen mode

Depends(verify_token) runs the token check before
the route logic. No valid token = no access.

Postman Tests

Signup

Signup success

Login - JWT token returned

Jwt token returned

Protected route - No token - 401

No token

Protected route - With token - Success

protected(token access)

Lessons Learned

JWT is stateless — the server doesn't store sessions.
The token itself contains everything needed to
identify the user. This is why it scales so well
in distributed systems.

Day 16 done. 14 more to go.

GDGoCBowen30dayChallenge

Top comments (0)