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.
Today’s scenario
Section titled “Today’s scenario”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 20Max 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 application
Section titled “The application”The login process from the previous tutorial is assumed to have already placed a user ID in the session:
request.session["user_id"] = 1Here is today’s relevant code:
from html import escape
from fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import HTMLResponse, RedirectResponsefrom 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.
Authentication gives us the actor
Section titled “Authentication gives us the actor”The browser sends:
GET /documents/101 HTTP/1.1Host: 127.0.0.1:8000Cookie: app_session=...SessionMiddleware verifies the signed cookie and reconstructs:
request.sessionSuppose 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.
Reading the session
Section titled “Reading the session”user_id = request.session.get("user_id")If the user successfully logged in earlier:
user_id == 1If no valid authenticated session exists:
user_id is NoneThe 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/101The route is registered as:
@app.get("/documents/{document_id}")FastAPI extracts:
"101"and converts it according to:
document_id: intThe 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 route authenticates the requester
Section titled “The route authenticates the requester”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 1Username: maxFirm: 10Role: memberNow authorization can begin.
Authorization requires an actor and an attempted action:
Actor: user 1Action: viewResource: document 101That gives us the real authorization question:
May user 1 view document 101?
Retrieving the resource
Section titled “Retrieving the resource”The route looks up the requested document:
document = documents_by_id.get(document_id)For:
document_id == 101the result is:
{ "id": 101, "firm_id": 10, "title": "Northstar Studio Website Review",}If the URL were:
/documents/777the dictionary would return:
NoneThe route handles that condition:
if document is None: raise HTTPException( status_code=404, detail="Document not found", )Why raise, not return
Section titled “Why raise, not return”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 FoundContent-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)
The authorization policy
Section titled “The authorization policy”Now we have both objects needed to make the decision:
userdocumentThe 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:
Trueif access is permittedFalseif access is denied
NIST describes authorization as deciding whether to permit or deny an entity access to a resource. (NIST authorization definition)
The administrator rule
Section titled “The administrator rule”if user["role"] == "admin": return TrueIf the user’s role is:
"admin"the function immediately returns:
TrueNo 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.
The ownership rule
Section titled “The ownership rule”If the user is not an administrator, execution continues:
return user["firm_id"] == document["firm_id"]For Max and document 101, Python evaluates:
10 == 10The result is:
TrueAccess is granted.
For Max and document 202, Python evaluates:
10 == 20The result is:
FalseAccess 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 Boolean expression
Section titled “The Boolean expression”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 firmThe two conditions are joined by or.
Only one must be true.
For an ordinary member:
is administrator? Falsesame firm? Truefinal result: TrueFor a member from another firm:
is administrator? Falsesame firm? Falsefinal result: FalseFor an administrator:
is administrator? Truesame firm? Irrelevantfinal result: TruePython 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.
Denying access
Section titled “Denying access”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:
Falsethen:
not Falsebecomes:
TrueThe body of the if statement runs, and the request ends with an error response.
Why return 404 instead of 403?
Section titled “Why return 404 instead of 403?”A direct authorization response might use:
403 ForbiddenThat 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 Foundfor both:
- A document that does not exist
- A document that exists but belongs to another firm
Why?
Suppose Max attempts:
/documents/202If the application returns:
403 Forbiddenit reveals something:
Document 202 probably exists, but you cannot see it.
An attacker could try:
/documents/201/documents/202/documents/203/documents/204Different 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.
When 403 is appropriate
Section titled “When 403 is appropriate”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
404when revealing the resource’s existence could expose information. - Use
403when the resource is known but the requested operation is forbidden.
The insecure version
Section titled “The insecure version”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 documentThe 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/101and then manually change the address to:
/documents/202The 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.
Hiding the link is not authorization
Section titled “Hiding the link is not authorization”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.
Where authorization should happen
Section titled “Where authorization should happen”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:
NoneThis 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.
Returning the authorized response
Section titled “Returning the authorized response”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=HTMLResponseThe response passes back through SessionMiddleware.
The server sends it to the browser:
HTTP/1.1 200 OKContent-Type: text/html; charset=utf-8The 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.
Three concrete request outcomes
Section titled “Three concrete request outcomes”Assume Max is logged in:
user_id = 1firm_id = 10role = "member"Request A: Max’s firm document
Section titled “Request A: Max’s firm document”GET /documents/101The decision:
User firm: 10Document firm: 10Same firm: yesResponse:
200 OKThe document is rendered.
Request B: another firm’s document
Section titled “Request B: another firm’s document”GET /documents/202The decision:
User firm: 10Document firm: 20Same firm: noAdmin: noResponse:
404 Not FoundThe document is not returned.
Request C: nonexistent document
Section titled “Request C: nonexistent document”GET /documents/777The lookup produces:
NoneResponse:
404 Not FoundFrom the browser’s perspective, requests B and C produce the same outcome.
The full execution trace
Section titled “The full execution trace”For an authorized request:
GET /documents/101Cookie: app_session=...the sequence is:
- The browser sends the request and session cookie.
- The server receives the HTTP message.
SessionMiddlewareverifies the cookie signature.- The middleware reconstructs
request.session. - The router matches
/documents/{document_id}. - FastAPI converts
"101"into the integer101. - FastAPI passes the
Requestobject and document ID to the route. get_authenticated_user()reads user ID1from the session.- The application retrieves user
1. - The application retrieves document
101. user_can_view_document()evaluates the authorization policy.- The user and document both belong to firm
10. - Authorization succeeds.
- The route generates HTML.
- FastAPI creates an
HTMLResponse. - The response passes outward through middleware.
- The server sends it to the browser.
- 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 includedThe architecture emerging
Section titled “The architecture emerging”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 browserThe 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.
The central idea
Section titled “The central idea”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.