Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 50 ยท Authentication and security

Roles, scopes and permissions

Protect FastAPI endpoints with role checks, OAuth2 scopes via Security(), and ownership rules, and learn when to answer 401, 403 or 404.

Knowing who is calling is only half of security. The other half is deciding what that caller may do. A regular member should not delete other people's posts, a read-only integration should not be able to write, and nobody should edit a note that belongs to someone else. This is authorization, and it comes after authentication.

In this lesson you build three layers of checks on top of a current-user dependency: roles ("admins only"), scopes ("this token may read posts but not write them") and ownership ("only the author may edit"). You will also settle the classic question of when to answer 401, 403 or 404. The examples use a simple lookup of fake tokens, so we can concentrate on the permission logic. Real tokens come from OAuth2 and JWT; the permission code is identical either way.

401 or 403?

The two codes are easy to mix up, and the names do not help (401 is literally called "Unauthorized").

  • 401 Unauthorized means "I do not know who you are." The credentials are missing, expired or invalid. The response should include a WWW-Authenticate header, and the client's reaction is to log in again.
  • 403 Forbidden means "I know who you are, and you may not do this." Logging in again will not help; the caller lacks the permission.

A third answer is sometimes better than 403: 404 Not Found. If a resource is private, answering 403 confirms that it exists. For things like other users' documents, returning 404 for "not yours" leaks nothing.

Which status code?

401 No valid identity. Log in again.
403 Known user, not allowed.
404 Hide that a private item exists.

Authentication first, then authorization.

1 / 2

Role-based checks

A role is a label on the user: admin, editor, member. The simplest way to guard an endpoint is a dependency that takes the current user and refuses anyone whose role is not on the list. Since the list differs per endpoint, build the dependency with a small factory function, the same idea as the configurable callable in Class and yield dependencies.

OAuth2PasswordBearer does the boring part: it reads the Authorization: Bearer <token> header, answers 401 when the header is missing, and teaches the docs page about the login URL.

Python Roles with a dependency factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the four lines as a ladder. Without a header the caller is nobody: 401. A garbage token is also 401. Bob is a valid user but a member: 403. Ann gets through. Because require_role builds on current_user, the identity check always runs first, so you can never reach the role check without being authenticated.

Compare roles to a fixed set of strings that you define in one place, ideally an Enum. A typo such as "admn" in a string comparison silently locks everyone out, while a misspelled enum member fails loudly at import time.

Scopes: permissions carried by the token

Roles describe the user. Scopes describe the token. A scope is a short string such as posts:read or posts:write that says what this particular token may do. Scopes let one person hand out limited access: a reporting tool gets a token with only posts:read, even though the user who created it could do much more.

FastAPI has first-class support for the OAuth2 scope convention:

  1. Declare the scopes you know about on the security scheme: OAuth2PasswordBearer(tokenUrl="token", scopes={...}). They show up in the docs.
  2. Require scopes on an endpoint with Security() instead of Depends(). Security works like Depends but also carries a scopes list.
  3. In the dependency, declare a parameter of type SecurityScopes. FastAPI fills it with the scopes required by the endpoint and by every dependency above it, so a dependency chain accumulates what it needs.

The dependency then compares the scopes the endpoint requires with the scopes the token grants.

Python OAuth2 scopes with Security() and SecurityScopes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The reader's token reads fine but gets 403 when it tries to write; the writer's token does both. The last line shows what the generated OpenAPI document records: the POST /posts operation requires posts:write, which is how Swagger UI knows what to show in its authorize dialog.

The scopes belong on the Security(current_user, scopes=[...]) in each endpoint, while the scheme object itself is still injected with a plain Depends(oauth2).

Scopes only mean something if the token issuer is honest about them. When a user logs in, the token endpoint decides which scopes to put in the token (often the intersection of what the client asked for and what the user may have). The endpoint code merely trusts the token. In OAuth2 password flow and JWT the scopes live inside a signed token, so clients cannot invent their own.

Roles or scopes?

Use roles when permissions follow the person and change rarely: a company's staff structure. Use scopes when permissions follow the token: third-party apps, API keys with limited power, short-lived tokens. Many real systems combine the two: roles decide the maximum, scopes narrow it per token.

Ownership checks

Neither roles nor scopes can answer "is this note yours?", because the answer depends on the data. Ownership checks live next to the data lookup. The usual shape is a helper that loads the item, treats "missing" and "not yours" the same way, and returns the item to the endpoint.

Python Only the owner (or an admin) may edit a note

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Cy, a stranger, gets 404, the same answer as for a note that does not exist, so Cy cannot even tell that note 1 is there. Bob owns it and Ann is an admin, so both succeed. Putting the check in a dependency means every endpoint that touches a single note (read, update, delete) shares one rule. That is much safer than repeating if note.owner != user.name in five places and forgetting it in the sixth.

A common bug class has its own name, BOLA (broken object-level authorization): an endpoint checks that the caller is logged in but never checks that the object belongs to them, so changing the id in the URL exposes other people's data. Ownership dependencies are the cure.

Design tips

  • Deny by default. Add the guard to the router or app first (see Router-level and global dependencies) and open specific endpoints explicitly.
  • Check on the server, always. Hiding a button in the front end is a convenience, not security.
  • Keep the rule in one place. A named dependency (require_role("admin"), get_own_note) is easy to read, test and audit.
  • Do not put secrets in error messages. Requires role: admin is fine; echoing the whole user record is not.
  • Test the negative cases. For every protected endpoint, write the test that proves the wrong caller is refused. Testing FastAPI apps shows how.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A request arrives with a valid token, but the user's role is member and the endpoint needs admin. Which status fits best?

    The caller is known (so not 401) but lacks permission, which is exactly 403.
  2. 2. What does the SecurityScopes parameter in a dependency contain?

    FastAPI fills it with the scopes demanded through Security(); your code compares them with the scopes the token grants.
  3. 3. Why might an ownership check answer 404 instead of 403 for another user's private note?

    Using the same 404 for missing and not-yours items leaks nothing about which ids exist.
  4. 4. Which describes a scope best?

    Roles describe users; scopes describe what a given token may do, so you can hand out limited tokens.

Summary

  • Authentication says who you are; authorization says what you may do. 401 means unknown caller, 403 means known but not allowed, and 404 can hide private items.
  • Role checks fit a dependency factory such as require_role("admin") built on a current-user dependency.
  • OAuth2 scopes use Security(dep, scopes=[...]) and SecurityScopes, and they appear in the OpenAPI document.
  • Ownership rules need the data, so put them in a dependency that loads the item and refuses strangers.
  • Deny by default, enforce on the server, keep each rule in one place and test the refusals.

Next: API keys and security practices covers API keys, CORS pitfalls, size limits and the wider API security checklist.