How Token Authentication Works
Understand the full authentication flow from registration to protected requests
The problem: every request is anonymous
Your API has no way to tell who sent a request. Anyone with the URL can create, delete, or modify any expense. You built the auth module in Lesson 1, but it is not connected to your app yet. No one can register or log in.
This lesson adds two endpoints — POST /register and POST /login — that connect your auth module to FastAPI. Here is the full flow they enable:
- Register: the user sends their email and password to
POST /register. The server hashes the password, stores the user, and returns the user's identifier and email. - Log in: the user sends the same email and password to
POST /login. The server verifies the credentials and returns a JWT (JSON Web Token). - Send authenticated requests: the user includes the JWT in the
Authorizationheader of every request:Authorization: Bearer. - Server verifies the token: the server decodes the JWT, extracts the email, and looks up the user. If the token is valid, the request proceeds. If not, the server returns a 401 error.
Tokens expire
The tokens you built in Lesson 1 expire after 30 minutes. After that, the user logs in again to get a new token. Some APIs use "refresh tokens" to extend sessions automatically, but that adds complexity. A 30-minute expiry keeps the system simple and secure.
What you will build
By the end of this lesson, you will have two working endpoints. Users can create accounts and receive JWT tokens. Lesson 3 uses get_current_user to lock down the expense endpoints so only authenticated users can access them.