# Requiring a Signed-In User

A get_current_user dependency reads the token from the Authorization header with OAuth2PasswordBearer, decodes it with PyJWT and loads the user from the database, so a route that asks for it serves only signed-in users and answers everyone else 401 with a WWW-Authenticate header.

Journeyman · FastAPI · REST API · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Require a signed-in user with a get_current_user dependency that reads the token with OAuth2PasswordBearer, decodes it and loads the user
- Answer 401 with a WWW-Authenticate header for a missing, made-up or expired token, and tell authentication apart from authorization

## Key takeaways

- Authentication is proving who you are, like a ticket at a concert hall's door. Authorization is deciding what a known user may do, like a badge for the staff room. Authentication comes first.
- OAuth2PasswordBearer(tokenUrl="auth/token") is a dependency that gives a route the token after the word Bearer in the Authorization header, and answers 401 by itself when there's none.
- get_current_user decodes the token with jwt.decode, which raises InvalidTokenError for a made-up, changed or expired token, and loads the user whose id is in the token's sub.
- Every refusal is 401 Unauthorized with the header WWW-Authenticate set to Bearer, which tells the caller to sign in and send a token.
- CurrentUser = Annotated[dict, Depends(get_current_user)] lets any route ask for the signed-in user with one parameter typed CurrentUser.

Most apps keep each person's things behind a sign-in: your orders, your messages, your team's to-do list. Signing in hands the app a token, and from then on every private request has to show it, and the API has to check it, every time. This lesson writes that check once, as a FastAPI dependency, and puts it on each route that needs it.

The example is Crew Board, a small team's task board: Maya is the admin, and Theo and Sofia are members. Its API keeps the team and their tasks in SQLite, and its sign-in route, `POST /auth/token`, works as in *Tokens: Signing In with a JWT*: the token it hands out holds the user's id, as text, in `"sub"`.

## Signed in, and nobody checks

Theo signs in and gets his token. But the task routes never ask for one, so a request with no token at all, `GET /tasks`, answers 200 OK with every task:

```json
[{"id":1,"title":"Book the room for the sprint demo","owner_id":1,"done":false},{"id":2,"title":"Write the release notes","owner_id":2,"done":false},{"id":3,"title":"Fix the typo on the sign-in page","owner_id":3,"done":true},{"id":4,"title":"Order new whiteboard markers","owner_id":2,"done":false}]
```

Handing out tokens protects nothing until something checks them. Think of a concert hall: a ticket gets you into the building, and a staff badge gets you into the staff room. An API checks the same two things, with their own names:

- **Authentication** is proving who you are. The request shows a token, and the API checks it.
- **Authorization** is deciding what a known user may do: Theo may change his own tasks, and only Maya may delete one.

Authentication comes first, because you can't decide what someone may do until you know who they are. This lesson is the ticket check at the door; *Roles and Ownership: 401 or 403* is the staff room.

![Two doors in a row. At the building's door, the ticket check asks who you are, which is authentication, and turns a request with no token or a bad one away with 401. At the staff room's door, the badge check asks what you may do, which is authorization, and turns a signed-in user without the right role away with 403](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/1fc011cbd2254dd1a2cc776921af8aea.webp)

## One check, written once

*Tokens: Signing In with a JWT* sent the token back in the request's `Authorization` header, after the word `Bearer`, and read it with `OAuth2PasswordBearer`:

```http
GET /tasks
Authorization: Bearer <Theo's token>
```

```python
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
```

As a dependency, `oauth2_scheme` hands a route the token after `Bearer `, or answers 401 by itself when there's none. `tokenUrl` names the sign-in route for the docs page.

That lesson's `/me` route decoded the token inside the route: a dozen lines. Crew Board has five task routes, so the first try is to copy those lines into each one. It works until someone adds a sixth route and forgets the copy, and nothing looks wrong. A check that guards every route belongs in one place, the way `get_db` keeps every connection in one place: a dependency.

## get_current_user: from a token to a user

A token is only text until it's checked. In Crew Board's `dependencies.py`:

```python
import sqlite3
from typing import Annotated

import jwt
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

import crew_data
from database import get_db
from security import ALGORITHM, SECRET_KEY

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")


def get_current_user(
    token: str = Depends(oauth2_scheme),
    conn: sqlite3.Connection = Depends(get_db, scope="function"),
):
    not_signed_in = HTTPException(
        status_code=401,
        detail="Your token isn't valid. Sign in again.",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except jwt.InvalidTokenError:
        raise not_signed_in
    user = crew_data.find_user(conn, int(payload["sub"]))
    if user is None:
        raise not_signed_in
    return user


CurrentUser = Annotated[dict, Depends(get_current_user)]
```

Read it from the top:

- `Depends(oauth2_scheme)` (read "depends on oauth2 scheme"): a dependency can depend on other dependencies. FastAPI runs `oauth2_scheme` first and passes its token in, and `get_db` gives the connection, with `scope="function"` so its commit comes before the answer goes out, as in *A Database Connection for Every Request*. FastAPI runs `get_db` once per request, so the route and `get_current_user` share one connection.
- `jwt.decode` checks the signature and the expiry time. A made-up token, one with a single letter changed, or one whose hour has run out raises `jwt.InvalidTokenError`. (An expired one raises `ExpiredSignatureError`, which is a kind of `InvalidTokenError`, so one `except` catches all three.)
- `"sub"` holds the user's id as text, and `int()` turns it back into a number. The user is loaded from the database, so someone removed from the team is turned away even with a real token.
- Each refusal is **401 Unauthorized**, read "401: I don't know who you are; sign in first". Its header `WWW-Authenticate: Bearer` tells the caller what kind of sign-in fixes it, and the error handler from *One Error Shape for the Whole API* passes it on.

The last line is a shorthand. `Annotated`, from `typing`, attaches extra information to a type hint, and FastAPI reads the `Depends` inside it. A route that needs the signed-in user now asks with one parameter:

```python
@router.get("")
def list_tasks(user: CurrentUser, conn: sqlite3.Connection = Depends(get_db, scope="function")):
    return crew_data.all_tasks(conn)
```

A route that needs the check but not the user can put it on its decorator instead: `dependencies=[Depends(get_current_user)]`.

## Three ways to be turned away

With `user: CurrentUser` on every task route, `GET /tasks` with no token answers 401 Unauthorized, in `oauth2_scheme`'s own words:

```json
{"status":401,"title":"Unauthorized","detail":"Not authenticated"}
```

With a made-up token, `Bearer not-a-real-token`, or with Theo's token after its hour has run out, `get_current_user` answers 401 too:

```json
{"status":401,"title":"Unauthorized","detail":"Your token isn't valid. Sign in again."}
```

All three carry the header `www-authenticate: Bearer`. With Theo's token in date, the same request answers 200 OK with the four tasks.

You can try it on the docs page. Start the app with `fastapi dev main.py` and open `http://127.0.0.1:8000/docs`: each task route now shows a padlock. Click **Authorize**, type `theo@example.com` as the username and `practice-theo` as the password, and click **Authorize** again. The page sends them to `/auth/token`, the `tokenUrl`, keeps the token, and adds the `Authorization` header to every request you try.

![FastAPI's docs page for Crew Board with the Authorize dialog open: the OAuth2PasswordBearer form asks for a username and a password, and the task routes behind it each show a padlock](https://www.ask-codey.com/lessons/TODO)

## Check yourself

2 questions to try on the lesson page.

## So what

One dependency on every private route means one place checks every token, so a request without a valid one is turned away with 401 before your route's code ever runs.

## Key terms

- [Authentication](https://www.ask-codey.com/glossary/authentication)
- [Authorization](https://www.ask-codey.com/glossary/authorization)
- [401 Unauthorized](https://www.ask-codey.com/glossary/401-unauthorized)
- [Bearer Token](https://www.ask-codey.com/glossary/bearer-token)
- [Security Dependencies](https://www.ask-codey.com/glossary/security-dependencies)

## Related

- [Tokens: Signing In with a JWT](https://www.ask-codey.com/lessons/fastapi-auth-tokens-jwt)
- [A Database Connection for Every Request](https://www.ask-codey.com/lessons/fastapi-data-get-db-dependency)
- [Roles and Ownership: 401 or 403](https://www.ask-codey.com/lessons/fastapi-auth-roles-and-ownership)
- [One Error Shape for the Whole API](https://www.ask-codey.com/lessons/fastapi-errors-one-shape)

Source: https://www.ask-codey.com/lessons/fastapi-auth-current-user-dependency
