Skip to main content
Now let’s create a proper dependency that validates tokens and returns the authenticated user. This is a crucial pattern you’ll use throughout your application.

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> header
2

get_current_user receives the token

get_current_user depends on oauth2_scheme, so it receives the extracted token
3

Token is decoded to find the user

fake_decode_token looks up the user based on the token
4

User is returned

If valid, the User object is returned. If invalid, an HTTPException is raised
5

Path operation receives the user

Your path operation receives the validated current_user object

Dependency Diagram

Adding an Active User Check

Let’s add another dependency layer to check if the user account is active:
Now the dependency chain is:
This pattern of chaining dependencies is very powerful. Each dependency handles one specific concern:
  • oauth2_scheme: Extract the token
  • get_current_user: Validate the token and get the user
  • get_current_active_user: Check if the user is active

Complete Example with Login

Here’s the complete working example:

Testing the Flow

1

Get a token

Response:
2

Use the token to access protected endpoints

Response:
3

Try with an inactive user

First get alice’s token, then try to use it:
Response:

What’s Still Missing?

This implementation still has security issues:
  • Fake token decoding: We’re treating the token as a username
  • No password hashing: Using "fakehashed" + password
  • No token expiration: Tokens never expire
  • No cryptographic signing: Anyone can forge tokens
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 use get_current_user or get_current_active_user in any endpoint:

Type Hints and Editor Support

Notice how we use type hints:
Your editor knows that current_user is a User object, so you get:
  • ✅ Autocompletion
  • ✅ Type checking
  • ✅ Inline documentation
FastAPI uses these type hints to automatically generate OpenAPI schemas, so your API documentation shows the correct response models.

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