Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 72 ยท Authentication and Security

Roles and Permissions

Decide what each logged-in user may do. Build role decorators, ownership checks and permission maps in Flask, and return clean 401 and 403 responses.

Logging a user in answers the question "who are you?". It says nothing about what that person is allowed to do. A customer must not open the admin panel, and a blogger must not delete somebody else's post. Deciding what an identified user may do is called authorization, and getting it wrong is one of the most common ways real applications leak data.

This lesson works with whatever login mechanism you chose, hand-made or Flask-Login. You will learn the difference between the 401 and 403 status codes, write a decorator that checks roles, add per-object ownership checks, centralize rules in a permission map, and show a friendly 403 page. The golden rule runs through everything: check on the server, every time. Hiding a button is a courtesy; it is never protection.

401 or 403?

Two status codes cover "you may not", and they mean different things:

  • 401 Unauthorized really means "unauthenticated": the server does not know who you are. Fix: log in. In a browser app you usually redirect to the login page instead of showing a 401.
  • 403 Forbidden: the server knows who you are and the answer is still no. Logging in again will not help.
flowchart TD
    A["Request to a protected view"] --> B{"Logged in?"}
    B -->|"no"| C["401 or redirect to login"]
    B -->|"yes"| D{"Has the required role<br/>or permission?"}
    D -->|"no"| E["403 Forbidden"]
    D -->|"yes"| F{"Owns this object<br/>(or is an admin)?"}
    F -->|"no"| E
    F -->|"yes"| G["200: do the work"]

Authentication comes first, then role checks, then checks on the specific object.

For the examples, a tiny helper keeps the setup short. The users live in a dictionary, and the test client logs in by writing the id straight into the session with session_transaction(), which is a convenient trick for tests. (A real app sets that value in its login view, as in Building a Login System.)

A decorator for roles

A role is a label such as "user", "editor" or "admin" attached to an account. The simplest rule says "this view needs one of these roles". Because the list of roles differs per view, the decorator needs an argument, so it is written as a function that returns a decorator (a decorator factory). If that shape is unfamiliar, Python decorators explains it.

Python roles_required and a JSON-aware 403 handler

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.

Look at the output table: anonymous visitors get 401 everywhere, a plain user gets 403, the editor passes only the editor route and the admin passes all three. The same abort(403) produces HTML for pages and JSON for /api/ URLs, because the error handler looks at the path. (Error handlers are covered in Error Handling and Custom Error Pages.)

Order matters when you stack decorators. Put the route decorator on top and the role check underneath, @app.get(...) then @roles_required(...), so the route registers the already-protected function. If you also use a login_required decorator, apply it outermost of the checks, so anonymous users hit the login redirect first.

Ownership: may you touch this object?

Roles answer "what kind of user are you?". Many rules depend on the object instead. Anybody may write a post, but only its author can edit it. This is called an ownership check, and forgetting it causes the famous bug where changing the number in a URL (/posts/17 to /posts/18) shows or edits another user's data. Security people call it insecure direct object reference.

The pattern is always the same: load the object, compare its owner with the current user, and refuse otherwise. Often admins are allowed too.

Python Ownership checks with an admin override

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.

Notice the order inside the view: authenticate (401), find the object (404), check permission (403), act. Cy's attempt to delete Bob's post fails with 403 and the data is unchanged.

403 or 404 for other people's objects?

Returning 403 admits that the post exists. For private data, such as someone's invoice, many apps return 404 instead, so outsiders cannot even confirm which ids are real. Choose one rule per resource type and apply it consistently. The common compromise: 403 for shared or public resources where existence is not a secret, 404 for private ones.

A permission map

When roles multiply, roles_required("admin", "editor", "moderator") lists spread across a codebase become hard to maintain. A cleaner design checks permissions, named actions such as "post:delete", and maps each role to its set of permissions in one place. Views ask "may this user do X?" and never mention role names. Changing what editors can do then means editing a single dictionary.

Python One table of role permissions

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 toolbar hides buttons a role cannot use, which makes the page tidier. But /users is protected independently with permission_required. A user who types the URL by hand still gets a 403. Always do both: hide in the template for usability, enforce in the view for security.

If you use Flask-Login, nothing changes except where the user comes from: use current_user.role instead of g.user["role"]. Add a can method to your user model if you prefer, and keep roles in a database table once users need more than one (a many-to-many relationship, see Relationships).

Common mistakes

  • Trusting the client. Never read the role or user id from a form field, query string or hidden input. Take it from the session or the database.
  • Checking only in the template. If the view has no check, anyone can call the URL directly.
  • Forgetting some methods. A page may be protected for GET while its POST handler is not. Apply the decorator to every method.
  • Forgetting nested routes and APIs. Protect JSON endpoints, file downloads and "export" routes the same way as pages.
  • Authorizing at list level only. Filtering a list to the user's own rows is good, but the detail, edit and delete views need their own checks.
  • Scattering rules. Put role names and permission checks in one module so they can be reviewed and tested together.
  • Not testing the negative. For every protected route, write tests for anonymous, wrong-role and wrong-owner requests, not only the happy path. See Testing Flask apps.

Ready-made role systems

The decorators above are enough for most apps. When you want users, roles, permissions and the registration, login and password-reset pages from one package, two extensions are common:

  • Flask-Security-Too adds a User and Role model on top of Flask-SQLAlchemy, with login, registration, password reset, email confirmation, two-factor authentication and the decorators @roles_required("admin"), @roles_accepted("editor", "admin") and @permissions_required(...).
  • Flask-Principal only deals with identity and permissions (needs, Permission(RoleNeed("admin"))), and leaves login to something else such as Flask-Login.
Python
# Flask-Security-Too (read-only: needs a database and several packages)
from flask_security import Security, SQLAlchemyUserDatastore, roles_required, current_user

user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

with app.app_context():
    user_datastore.find_or_create_role(name="teacher")
    user_datastore.find_or_create_role(name="student")
    user_datastore.create_user(email="[email protected]", password=hash_password("s3cret"),
                               roles=["teacher"])
    db.session.commit()

@app.get("/teachers")
@roles_required("teacher")          # 403 for everybody else
def teachers():
    return f"Welcome, {current_user.email}"

A typical role-based app (a school site with teacher and student pages, for example) therefore has three parts: a table of users, a table of roles linked many-to-many (Relationships), and one decorator per protected view. Whichever tool you use, keep the rule from the start of this lesson: check on the server, answer 401 when nobody is logged in and 403 when the wrong person is.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A logged-in user without the admin role requests /admin. Which status code fits best?

    The server knows who the user is, and the answer is still no, so 403 Forbidden. 401 means the user is not authenticated.
  2. 2. What is the difference between a role check and an ownership check?

    Roles describe kinds of users. Ownership describes the relationship between one user and one object, such as the author of a post.
  3. 3. Why is hiding the 'Delete' button from non-admins not enough?

    Templates control what is displayed, not what is allowed. The server-side check is the actual protection.
  4. 4. Why might an app answer 404 instead of 403 for someone else's private invoice?

    A 403 reveals that the resource exists. For private data a 404 leaks less.
  5. 5. In which order should a view that edits a post check things?

    Each step needs the result of the previous one: you must know who the user is and which object it is before judging the permission.

Summary

  • Authentication says who you are; authorization says what you may do. Enforce authorization on the server for every route and method.
  • Use 401 (or a redirect to login) when the user is unknown and 403 when a known user is not allowed.
  • A decorator factory such as roles_required("admin") keeps role checks short and consistent.
  • Ownership checks compare an object's owner with the current user; skipping them lets users edit each other's data by changing an id in the URL.
  • A permission map (role -> set of actions) keeps rules in one place; expose a can() helper to templates for hiding controls.
  • Return 404 for private objects when even their existence should stay secret, and test anonymous, wrong-role and wrong-owner requests.

Next: Web Security Essentials, CSRF, XSS, SQL injection, cookies and headers.