Skip to content

04 · Authorization and Resource Ownership

In the previous tutorial, the application authenticated a user through a signed session cookie.

The application could answer:

This request came from user 1.

Today we add the next question:

Is user 1 allowed to access this particular document?

That is authorization.

Our lifecycle now becomes:

Browser → session middleware → authentication → router → resource lookup → authorization → response

The critical lesson is that successful login does not grant unlimited access.

Imagine a document-review application serving several organizations.

Every user belongs to a firm, and every document belongs to a firm:

Max
└── Firm 10
Sara
└── Firm 20
Document 101
└── Firm 10
Document 202
└── Firm 20

Max may access document 101 because they belong to the same firm.

Max may not access document 202, even if he manually enters its URL.

We will also include an administrator who is allowed to access documents across firms.

The login process from the previous tutorial is assumed to have already placed a user ID in the session:

request.session["user_id"] = 1

Here is today’s relevant code:

from html import escape
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from starlette.middleware.sessions import SessionMiddleware
app = FastAPI()
app.add_middleware(
SessionMiddleware,
secret_key="replace-this-with-a-random-secret",
session_cookie="app_session",
same_site="lax",
https_only=False,
)
users_by_id = {
1: {
"id": 1,
"username": "max",
"firm_id": 10,
"role": "member",
},
2: {
"id": 2,
"username": "sara",
"firm_id": 20,
"role": "member",
},
99: {
"id": 99,
"username": "admin",
"firm_id": None,
"role": "admin",
},
}
documents_by_id = {
101: {
"id": 101,
"firm_id": 10,
"title": "Northstar Studio Website Review",
},
202: {
"id": 202,
"firm_id": 20,
"title": "Harbor Studio Document Review",
},
}
def get_authenticated_user(request: Request):
user_id = request.session.get("user_id")
if user_id is None:
return None
return users_by_id.get(user_id)
def user_can_view_document(user: dict, document: dict):
if user["role"] == "admin":
return True
return user["firm_id"] == document["firm_id"]
@app.get(
"/documents/{document_id}",
response_class=HTMLResponse,
)
async def document_page(
request: Request,
document_id: int,
):
user = get_authenticated_user(request)
if user is None:
return RedirectResponse(
url="/login",
status_code=303,
)
document = documents_by_id.get(document_id)
if document is None:
raise HTTPException(
status_code=404,
detail="Document not found",
)
if not user_can_view_document(user, document):
raise HTTPException(
status_code=404,
detail="Document not found",
)
return f"""
<html>
<body>
<h1>{escape(document["title"])}</h1>
<p>Document ID: {document["id"]}</p>
<p>Firm ID: {document["firm_id"]}</p>
<p>Viewed by: {escape(user["username"])}</p>
</body>
</html>
"""

We are still using Python dictionaries in place of database tables.

Here, “firm” simply means an organization using the application. firm_id is our example’s organization boundary. The string values are escaped before entering HTML, using html.escape(); permission to view a value does not make that value safe markup.

Later, SQLAlchemy will retrieve the same information from SQLite. The authorization logic, however, will remain conceptually similar.


The browser sends:

GET /documents/101 HTTP/1.1
Host: 127.0.0.1:8000
Cookie: app_session=...

SessionMiddleware verifies the signed cookie and reconstructs:

request.session

Suppose its contents are:

{"user_id": 1}

Our helper function reads that information:

def get_authenticated_user(request: Request):
user_id = request.session.get("user_id")
if user_id is None:
return None
return users_by_id.get(user_id)

Let’s break this down carefully.

user_id = request.session.get("user_id")

If the user successfully logged in earlier:

user_id == 1

If no valid authenticated session exists:

user_id is None

The session stores only an identifier. It does not contain the entire authoritative user record.

That is intentional.

The next line retrieves the current user from application storage:

return users_by_id.get(user_id)

In this tutorial, the storage is a dictionary.

In the eventual SQLAlchemy version, it will resemble:

user = db.get(User, user_id)

Why perform another lookup if the session already contains the user ID?

Because the session only tells us which user previously logged in. The application still needs current information about that user:

  • Does the account still exist?
  • Is it active?
  • Which firm does it currently belong to?
  • What role does it currently have?
  • Were its permissions changed?

The database should remain the authoritative source.

If an administrator changes someone’s role, we do not want an old session cookie to preserve the former permissions indefinitely.


The router receives an untrusted document ID

Section titled “The router receives an untrusted document ID”

The URL is:

/documents/101

The route is registered as:

@app.get("/documents/{document_id}")

FastAPI extracts:

"101"

and converts it according to:

document_id: int

The route function conceptually receives:

await document_page(
request=current_request,
document_id=101,
)

The value is now a valid Python integer.

But valid does not mean authorized.

This distinction is extremely important.

FastAPI has confirmed:

101 is a valid integer.

FastAPI has not confirmed:

The current user is allowed to access document 101.

Type validation and authorization solve different problems.


The first operation inside the route is:

user = get_authenticated_user(request)

For the session:

{"user_id": 1}

the result is:

{
"id": 1,
"username": "max",
"firm_id": 10,
"role": "member",
}

The route then checks:

if user is None:
return RedirectResponse(
url="/login",
status_code=303,
)

If authentication failed, the application redirects the browser to the login page.

If authentication succeeded, we know the actor:

User 1
Username: max
Firm: 10
Role: member

Now authorization can begin.

Authorization requires an actor and an attempted action:

Actor: user 1
Action: view
Resource: document 101

That gives us the real authorization question:

May user 1 view document 101?


The route looks up the requested document:

document = documents_by_id.get(document_id)

For:

document_id == 101

the result is:

{
"id": 101,
"firm_id": 10,
"title": "Northstar Studio Website Review",
}

If the URL were:

/documents/777

the dictionary would return:

None

The route handles that condition:

if document is None:
raise HTTPException(
status_code=404,
detail="Document not found",
)

HTTPException is a Python exception containing information FastAPI can convert into an HTTP error response.

We write:

raise HTTPException(...)

not:

return HTTPException(...)

Raising the exception immediately stops normal execution.

FastAPI catches it and creates a response resembling:

HTTP/1.1 404 Not Found
Content-Type: application/json
{"detail": "Document not found"}

No lines below the raise statement execute.

FastAPI’s documentation specifically distinguishes this from returning an ordinary value: HTTPException is raised, allowing it to terminate request processing immediately. (FastAPI error-handling documentation)


Now we have both objects needed to make the decision:

user
document

The route calls:

user_can_view_document(user, document)

Here is that function:

def user_can_view_document(user: dict, document: dict):
if user["role"] == "admin":
return True
return user["firm_id"] == document["firm_id"]

This function represents the application’s authorization policy.

It accepts:

  • The actor
  • The resource

It returns:

  • True if access is permitted
  • False if access is denied

NIST describes authorization as deciding whether to permit or deny an entity access to a resource. (NIST authorization definition)

if user["role"] == "admin":
return True

If the user’s role is:

"admin"

the function immediately returns:

True

No firm comparison is needed.

That is the application’s stated policy:

Administrators may view documents belonging to any firm.

Whether that is a good policy depends on the product. In a real document platform, you might need more restrictive roles:

  • Firm administrator
  • document reviewer
  • Member
  • Read-only user
  • Platform operator

Today, we only need enough complexity to see the decision clearly.

If the user is not an administrator, execution continues:

return user["firm_id"] == document["firm_id"]

For Max and document 101, Python evaluates:

10 == 10

The result is:

True

Access is granted.

For Max and document 202, Python evaluates:

10 == 20

The result is:

False

Access is denied.

The user and the document both exist. The user is correctly authenticated. The denial happens because the user does not have access to that particular resource.


The same authorization rule could be written in one expression:

return (
user["role"] == "admin"
or user["firm_id"] == document["firm_id"]
)

This means:

Permit access if:
the user is an administrator
OR
the user and document belong to the same firm

The two conditions are joined by or.

Only one must be true.

For an ordinary member:

is administrator? False
same firm? True
final result: True

For a member from another firm:

is administrator? False
same firm? False
final result: False

For an administrator:

is administrator? True
same firm? Irrelevant
final result: True

Python short-circuits or.

If the first condition is already True, it does not need to evaluate the second condition to know that the entire expression is true.

The longer version used in the application makes the special administrator rule easier to see.


The route checks the result:

if not user_can_view_document(user, document):
raise HTTPException(
status_code=404,
detail="Document not found",
)

If the authorization function returns:

False

then:

not False

becomes:

True

The body of the if statement runs, and the request ends with an error response.


A direct authorization response might use:

403 Forbidden

That status means:

The server understood who you are, but you do not have permission to perform this action.

That is semantically accurate.

Our example intentionally uses:

404 Not Found

for both:

  • A document that does not exist
  • A document that exists but belongs to another firm

Why?

Suppose Max attempts:

/documents/202

If the application returns:

403 Forbidden

it reveals something:

Document 202 probably exists, but you cannot see it.

An attacker could try:

/documents/201
/documents/202
/documents/203
/documents/204

Different responses might let the attacker discover valid document IDs.

Returning the same 404 response for missing and inaccessible documents reveals less information:

{"detail": "Document not found"}

The application behaves as though documents belonging to other firms do not exist from this user’s perspective.

A 403 can still be perfectly appropriate.

For example, imagine a visible document with an edit button available only to administrators.

A member may be allowed to view the document but not approve it:

if user["role"] != "admin":
raise HTTPException(
status_code=403,
detail="Administrator access required",
)

The document’s existence is not secret. The user simply lacks permission for the requested action.

A practical distinction is:

  • Use 404 when revealing the resource’s existence could expose information.
  • Use 403 when the resource is known but the requested operation is forbidden.

Consider this route:

@app.get("/documents/{document_id}")
async def document_page(document_id: int):
document = documents_by_id.get(document_id)
if document is None:
raise HTTPException(
status_code=404,
detail="Document not found",
)
return document

The route confirms that the document exists, then returns it.

It never asks:

Who is the current user?

or:

Does this user own this document?

Max could log in, view:

/documents/101

and then manually change the address to:

/documents/202

The browser would send a normal request for document 202, and the application would return it.

Nothing about the browser prevents users from changing URLs.

Nothing about a hidden link prevents them from constructing requests manually.

Nothing about FastAPI’s integer validation provides authorization.

That is why authorization must be enforced on the server for every protected resource request.


Suppose the dashboard only displays this link to Max:

<a href="/documents/101">
View document
</a>

It does not display:

<a href="/documents/202">
View document
</a>

That improves the interface, but it does not secure document 202.

A user can still:

  • Edit the URL
  • Use browser developer tools
  • Send a request with curl
  • Use an API client
  • Modify JavaScript
  • Replay an earlier request

Frontend visibility and backend permission are separate concerns.

The browser may help the user follow the intended workflow. Only the server can enforce access.


In this tutorial, authorization happens after retrieving the document:

document = documents_by_id.get(document_id)
if not user_can_view_document(user, document):
raise HTTPException(...)

That makes the policy easy to understand.

With SQLAlchemy, we could enforce tenant ownership as part of the database query:

document = db.scalar(
select(Document).where(
Document.id == document_id,
Document.firm_id == user.firm_id,
)
)

This asks the database:

Return document 101 only if it belongs to the current user’s firm.

For an unauthorized user, the result is simply:

None

This is often safer than loading a document globally and remembering to check its firm afterward.

It naturally treats inaccessible documents as nonexistent.

However, administrator access may require a slightly different query or policy branch.

The eventual structure might be:

if user.role == "admin":
document = get_document_by_id(document_id)
else:
document = get_firm_document(
document_id=document_id,
firm_id=user.firm_id,
)

The important rule is not that authorization must always be performed in one exact layer.

The important rule is:

Protected data must never leave the server unless the authorization decision has succeeded.


If authorization succeeds, execution reaches:

return f"""
<html>
<body>
<h1>{escape(document["title"])}</h1>
<p>Document ID: {document["id"]}</p>
<p>Firm ID: {document["firm_id"]}</p>
<p>Viewed by: {escape(user["username"])}</p>
</body>
</html>
"""

FastAPI wraps the string in an HTMLResponse because the route declares:

response_class=HTMLResponse

The response passes back through SessionMiddleware.

The server sends it to the browser:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8

The browser parses and renders the HTML.

At no point does the browser make the authorization decision.

The browser only receives the successful document page because the server already approved access.


Assume Max is logged in:

user_id = 1
firm_id = 10
role = "member"
GET /documents/101

The decision:

User firm: 10
Document firm: 10
Same firm: yes

Response:

200 OK

The document is rendered.

GET /documents/202

The decision:

User firm: 10
Document firm: 20
Same firm: no
Admin: no

Response:

404 Not Found

The document is not returned.

GET /documents/777

The lookup produces:

None

Response:

404 Not Found

From the browser’s perspective, requests B and C produce the same outcome.


For an authorized request:

GET /documents/101
Cookie: app_session=...

the sequence is:

  1. The browser sends the request and session cookie.
  2. The server receives the HTTP message.
  3. SessionMiddleware verifies the cookie signature.
  4. The middleware reconstructs request.session.
  5. The router matches /documents/{document_id}.
  6. FastAPI converts "101" into the integer 101.
  7. FastAPI passes the Request object and document ID to the route.
  8. get_authenticated_user() reads user ID 1 from the session.
  9. The application retrieves user 1.
  10. The application retrieves document 101.
  11. user_can_view_document() evaluates the authorization policy.
  12. The user and document both belong to firm 10.
  13. Authorization succeeds.
  14. The route generates HTML.
  15. FastAPI creates an HTMLResponse.
  16. The response passes outward through middleware.
  17. The server sends it to the browser.
  18. The browser renders the document.

For an unauthorized request, the flow stops at step 12:

Authorization fails
↓
HTTPException is raised
↓
Normal route execution stops
↓
FastAPI creates a 404 response
↓
The protected document is never included

We now have several different responsibilities:

SessionMiddleware
└── Reconstructs the signed browser session
get_authenticated_user()
└── Determines who the requester is
Router
└── Matches the HTTP method and path
Document lookup
└── Retrieves the requested resource
user_can_view_document()
└── Applies the authorization policy
Route
└── Coordinates the HTTP-specific sequence
HTMLResponse
└── Carries permitted content back to the browser

The authorization rule is deliberately separated:

user_can_view_document(user, document)

The route does not need to contain every permission detail itself.

Later, FastAPI’s dependency system will let us move authentication and reusable authorization requirements out of individual route bodies.

Instead of every protected route manually doing this:

user = get_authenticated_user(request)
if user is None:
...
if not user_can_view_document(user, document):
...

a route will be able to declare its requirements:

current_user = Depends(get_current_user)

That is the bridge to dependency injection.

Authentication identifies the actor:

This is user 1.

Authorization evaluates the actor, action, and resource together:

May user 1 view document 101?

A secure route does not merely confirm that someone is logged in. It verifies that the authenticated user has permission for the exact resource and action being requested.

The browser supplies the URL.

FastAPI validates the URL’s shape.

Your application decides whether that user is allowed to receive the resource.