AlgoViz

API authorization

medium 24 min

Authorization decides what a known caller may do, to which object, right now.

Video lesson · Chapter 1 of 6

Start with roles

0:00 / 3:43

API authorization

1:18Reel

Theory

Read or listen first. About 2 min.

What it is

Authorization decides whether a caller may perform an action on a thing. It starts where authentication ends: the caller's identity is already known.

Every decision has four inputs: the subject (who), the action (what), the resource (on which object) and the context (when, from where). The answer is allow or deny.

Why it exists

Knowing who someone is does not make their request safe. A real, logged-in customer can still ask for another customer's order. If nobody checks, they get it.

Good authorization limits damage. A stolen account, a buggy script or a partner app can only reach what it was given. It also answers auditors, who ask who was able to do what, and why.

A short history

  1. 1975

    Saltzer and Schroeder describe least privilege and fail-safe defaults: start with no access, and grant only what is needed.

  2. 1992

    David Ferraiolo and Richard Kuhn formalise role-based access control (RBAC).

  3. February 2004

    The NIST model for RBAC becomes American national standard INCITS 359.

  4. January 2014

    NIST publishes SP 800-162, a guide to attribute-based access control (ABAC).

  5. 2019

    Google describes Zanzibar, a global authorization system built on relationships, at USENIX ATC.

  6. 2021

    Broken access control moves from fifth to first place in the OWASP Top 10.

Words to know

Permission
The right to do one action on one kind of thing, such as products:read.
Role
A named set of permissions, such as seller.
Scope
A limit on what an app may do for a user. It never gives more than the user has.
Ownership check
Comparing the caller with the owner of the exact object.
Tenant
One customer organisation whose data must stay apart from the others.
Least privilege
Give the smallest set of rights that does the job.
Policy decision point
The part that answers allow or deny. The enforcement point asks it and obeys.
BOLA
Broken object level authorization: the server forgets to check the object. First in the OWASP API list of 2023.

How it works

Step through the idea, or press Play.

Step 1 of 3

Identify. Authentication says who the caller is

Understand it

Start here

The swimming pool story

At a swimming pool, everyone shows a ticket at the entrance and gets a wristband. Being inside does not mean you may go everywhere.

What a wristband opens
SWIMMING POOLmanagervisitor

Role, owner, time: three different questions, and a real API often needs all three.

Authentication

  • Who are you?
  • Verifies identity: login, JWT, session
  • Returns a user ID such as usr_123
  • Fails with 401

Authorization

  • What may you do?
  • Checks permissions: roles, policies, scopes
  • Returns allowed or denied
  • Fails with 403, or 404 to hide that a thing exists

One request, two checks

The object check needs the object, so it usually lives in the service, next to the data.

Why

What happens without it

With authorization

  • Only admins delete products
  • Each role sees its own dashboard
  • Sellers reach only their own stock
  • People see only their own orders

Without it

  • Any user can delete products
  • Customers open admin pages
  • Sellers read other sellers' data
  • Every order is visible to everyone

Models

Four ways to write the rules

  • Access list (ACL)

    Each object lists who may do what to it. Simple for files and shared documents.

  • Roles (RBAC)

    Users get roles, roles get permissions. Easy to understand and to audit.

  • Attributes (ABAC)

    Rules compare facts about user, object, action and situation. Flexible, and harder to review.

  • Relationships (ReBAC)

    Access follows links: editor of this folder, member of that team. Good for sharing.

Which model do I need?

The models combine. Roles for staff, ownership for customers and scopes for partners is a common mix.

Model 1

Roles: RBAC

Permissions belong to roles, and users are given roles. When somebody changes job, you change one role assignment instead of thirty permissions.

The shop's roles

PermissionCustomerSellerAdmin
View productsYesYesYes
Create a productNoYesYes
Edit a productNoOwn onlyYes
Delete a productNoNoYes
View and edit a cartOwn onlyNoYes
Place an orderYesNoYes
View ordersOwn onlyOwn sales onlyYes
Manage stockNoOwn onlyYes
Manage usersNoNoYes
"Own only" is where a role is not enough: the code must also compare the owner.

Why roles save work

10,000×30=300,000;grantsvs10,000+5×30=10,15010{,}000 \times 30 = 300{,}000 ;\text{grants} \quad\text{vs}\quad 10{,}000 + 5 \times 30 = 10{,}150
Assumed: 10,000 users, 30 permissions, 5 roles, one role each.

RBAC is good at

  • Easy to understand and manage
  • A clear audit trail
  • Scales well for most applications
  • Little maintenance
  • Supported by most frameworks

RBAC struggles with

  • Role explosion in complex systems
  • Decisions that need context
  • Rules that change with the situation
  • Ownership of single objects
  • Many tenants, unless roles are per tenant

Role explosion

4;departments×5;regions×3;levels=60;roles4;\text{departments} \times 5;\text{regions} \times 3;\text{levels} = 60 ;\text{roles}
When a role name starts to contain facts (seller-north-junior), those facts should be attributes.

Model 2

Attributes: ABAC

Four kinds of attribute

KindQuestionExamples
SubjectWho is asking?role, department, clearance, location
ResourceWhat are they touching?owner, type, classification, status
ActionWhich operation?read or write, sensitivity, impact
EnvironmentIn which situation?time, IP address, device type, risk score
Text
# Sellers edit their own productsPERMIT IF subject.role == "seller" AND action == "update"      AND resource.type == "product" AND resource.owner == subject.id# Customers cancel their own pending orders within 24 hoursPERMIT IF subject.id == order.customer_id AND action == "cancel"      AND (now - order.created_at) < 24 hours AND order.status == "pending"# Premium customers get the holiday discount of 20%PERMIT IF subject.membership == "premium" AND action == "apply_discount"      AND env.is_holiday_sale == true
Three policies of the shop.

RBAC or ABAC?

SituationRBACABAC
Simple app, few rolesBestMore than you need
Ownership of objectsNeeds extra codeA natural rule
Office hours onlyNot by itselfEasy
Many tenantsRoles per tenant, or extra codeNatural: compare tenant IDs
AuditEasy: list the rolesDetailed logs, harder to answer "who can?"

Model 3

OAuth scopes

A scope says what an app may do for a user. The user sees the list and agrees. A scope can only narrow what the user already has.

What the app can really do

allowed=scopes granted to the app;∩;permissions of the user\text{allowed} = \text{scopes granted to the app} ;\cap; \text{permissions of the user}
If the app holds delete and the user may not delete, the answer is no. If the user may and the app does not hold the scope, the answer is also no.

Scope examples

ScopeAllowsNote
products:readView productsAlso written read:products; pick one order
products:writeCreate and updateDoes not include delete
products:deleteDeleteSensitive, asked for separately
cart:writeChange the cart
orders:readView ordersOnly the orders this user may see
users:adminManage usersRarely given to other apps

Consent

The partner gets exactly what the user agreed to and nothing more.

Practice

Three patterns that matter most

PatternWrongRight
Check on the serverHide the delete button in the browserThe server checks and answers 403. Hiding the button is only good manners
Least privilegeGive admin because someone needs reportsGive reports:read
Deny by defaultAllow unless it is on a block listDeny unless a rule allows it
JavaScript
const requirePermission = (permission) => (req, res, next) => {  if (!req.user.permissions.includes(permission)) {    audit.denied(req.user.id, permission);    return res.status(403).json({ error: "forbidden" });  }  next();};app.delete("/products/:id",  authenticate,                         // 1. who are you?  requirePermission("products:delete"), // 2. may you do this kind of thing?  deleteProductHandler                  // 3. may you touch this object? then do it);
Middleware for the endpoint check. The order matters.
SQL
SELECT * FROM orders WHERE id = :order_id   AND tenant_id = :tenant_of_caller   AND customer_id = :caller_id;
Put owner and tenant in the query. A row that is not theirs is simply not found.

403 or 404?

For other people's private objects, 404 avoids confirming that the ID is real. Error shapes are in API error handling.

Architecture

Where the decision is made

Coarse at the edge, fine next to the data

A client calls the API gateway, which checks token and scopes and forwards to the orders service. The orders service asks a policy engine running beside it on the same machine, and reads orders from PostgreSQL. A policy repository sends rules to the engine, and decisions go to an audit log.
The gateway checks token and scopes. The service checks the object, and asks a policy engine on the same machine (orange).

Three places to decide

PlaceGoodCost
In each service's codeSimple, fast, has the dataRules are copied and drift apart
Policy engine beside each serviceOne language, local calls, tested apartRules and data must be distributed
Central authorization serviceOne answer for all, shares and groupsEvery call depends on it: needs caching, a timeout and high availability

Checking a list

20×5 ms=100 msone batch≈8 ms20 \times 5\,\text{ms} = 100\,\text{ms} \qquad\text{one batch} \approx 8\,\text{ms}
Assumed numbers for a page of 20 items and a remote check. Filter in the query, or ask once for the whole batch.

Freshness

Roles inside tokens grow old

If a JWT carries role: admin and you remove the role, the token still says admin until it expires. Keep tokens short, or carry only the user ID and read roles at the service. For dangerous actions always read the current role.

How old may a right be?

ActionSource of the roleOldest answer
Read a product listToken15 minutes
Edit stockCache30 seconds
Refund, delete, change rolesDatabaseNow
Example choices. Say yours in an interview.

Operations

Test it and record it

  1. 1

    Keep a permission matrix as a test

    For each role and endpoint, assert allow or deny. A new endpoint without a row fails the build.

  2. 2

    Always test with two users

    User B tries to read, change and delete what user A owns. Expect 403 or 404 each time.

  3. 3

    Log each denial

    Who, what, which object, which rule. Many denials from one caller is a warning sign.

  4. 4

    Review rights

    Remove roles that nobody used for months. Give dangerous rights for a limited time.

Summary

The whole topic in one minute.

Check on the server, on every request, at two levels: may this caller use this endpoint, and may they touch this object? Deny unless a rule allows it.

Start with a few roles plus ownership and tenant checks. Add attributes when rules depend on time, state or place, relationships when people share things with people, and scopes whenever another app acts for a user.

  • Authorization asks what a known caller may do, to which object, in which situation.
  • Check on the server, on every request, at endpoint level and at object level.
  • Roles for jobs, ownership and tenant for objects, attributes for context, scopes for other apps.
  • Deny by default and give the least that works.
  • Rights in tokens and caches are old copies. Decide how old is acceptable for each action.

Sources