The User Model
First, let’s define proper Pydantic models for our users:UserInDB inherits from User and adds the hashed_password field. We never return this model directly—it’s only for internal use.Creating the get_current_user Dependency
Now let’s create a dependency that converts a token into a user:How the Dependency Chain Works
This is where FastAPI’s dependency injection really shines:1
OAuth2 scheme extracts the token
oauth2_scheme extracts the token from the Authorization: Bearer <token> header2
get_current_user receives the token
get_current_user depends on oauth2_scheme, so it receives the extracted token3
Token is decoded to find the user
fake_decode_token looks up the user based on the token4
User is returned
If valid, the
User object is returned. If invalid, an HTTPException is raised5
Path operation receives the user
Your path operation receives the validated
current_user objectDependency Diagram
Adding an Active User Check
Let’s add another dependency layer to check if the user account is active:Complete Example with Login
Here’s the complete working example:Testing the Flow
1
Get a token
2
Use the token to access protected endpoints
3
Try with an inactive user
First get alice’s token, then try to use it:Response:
What’s Still Missing?
Let’s fix all of these issues in the next section!Reusing the get_current_user Dependency
The beauty of this pattern is that you can useget_current_user or get_current_active_user in any endpoint:
Type Hints and Editor Support
Notice how we use type hints:current_user is a User object, so you get:
- ✅ Autocompletion
- ✅ Type checking
- ✅ Inline documentation
Next Steps
Now let’s implement proper security with JWT tokens and password hashing:OAuth2 with JWT
Learn how to implement proper JWT token authentication with secure password hashing