Writing Authorization Checks With LLMs in November 2026: Deny by Default, Check Ownership on Every Request, and Test as the Wrong User

Ask a coding assistant for an endpoint that returns an invoice, and you will usually get working code in seconds. It reads the invoice ID from the URL, loads the row, and sends it back as JSON. It also, very often, forgets to ask the only question that matters for security: is this user allowed to see this invoice?

Broken access control has sat at or near the top of the OWASP Top 10 for years, and it is exactly the kind of bug LLMs produce by default. Authentication ("who are you?") tends to be handled by a framework or middleware the model can see. Authorization ("what may you do with this specific thing?") depends on business rules that live in your head, your database schema, and your product decisions. The model cannot guess them, so it often leaves them out.

This post is a practical workflow for using LLMs to write authorization code without shipping the classic hole where changing /invoices/1041 to /invoices/1042 shows you someone else's data.

Exit light on a turnstile in a New York City subway station

Getting into the station is authentication. Each turnstile still decides, every time, whether this particular person may pass. Image: NYC Subway Turnstile Exit Light by Louis Brickman, CC BY-SA 3.0, via Wikimedia Commons.

Why models get authorization wrong

It helps to know the failure patterns before you start prompting. In generated code, these show up again and again:

  • Login check only. The route is wrapped in @login_required or an auth middleware, so any signed-in user can read or change any record.
  • Lookup by ID alone. Invoice.objects.get(id=invoice_id) instead of a query scoped to the current user or tenant.
  • Trusting client-supplied roles or owners. The request body carries "role": "admin" or "owner_id": 7 and the code saves it as-is.
  • Checks in the UI only. The "Delete" button is hidden for non-admins, but the API endpoint behind it accepts anyone.
  • Inconsistent coverage. The read endpoint checks ownership; the update, export, and bulk-delete endpoints written later do not.
  • Allow by default. A permission helper returns True when it does not recognize the action, instead of refusing.

None of these are exotic. They are what you get when a model optimizes for "make the feature work" and nobody told it the rules.

Step 1: Write the rules down before you prompt

The single biggest improvement is giving the model an explicit permission table. Keep it short and concrete. For a small invoicing app it might look like this:

Resources: Organization, Invoice, Member

Roles (per organization): owner, admin, member, viewer

Invoice
  read     : any role in the invoice's organization
  create   : owner, admin, member
  update   : owner, admin; member only if they created it AND status == "draft"
  delete   : owner, admin; never if status == "paid"
  export   : owner, admin

Member
  invite   : owner, admin
  change role : owner only; nobody can change their own role
  remove   : owner, admin; cannot remove the last owner

Default  : deny anything not listed

Writing this table forces you to make decisions you would otherwise leave to the model by accident: can a member edit a sent invoice? Can an admin promote themselves? The table also becomes the spec your tests check against later.

Step 2: Give the model the real code, not a description

Paste the pieces the model needs to see: your data models (especially the foreign keys that link records to users and tenants), how the current user is loaded, and one existing endpoint you consider correct. Then ask for a narrow change.

A prompt that works well:

Here is my permission table (below), my models, and my current
invoice routes. Write a single function

  can(user, action, invoice) -> bool

that implements ONLY the Invoice rules in the table. Requirements:
- Return False for any action not in the table.
- Look up the user's role from the membership table, never from
  the request.
- Do not change any route yet.
After the code, list every rule from the table and point to the
line that enforces it.

Asking the model to map each rule to a line is a cheap way to catch omissions. If it cannot point to where "never delete a paid invoice" is enforced, it probably is not enforced.

Step 3: Deny by default and centralize the decision

Scattering if user.is_admin across fifty handlers is how coverage gaps appear. Put every decision in one place and make the unknown case fail closed. A minimal Python version:

RULES = {
    "read":   lambda u, inv, role: role is not None,
    "create": lambda u, inv, role: role in {"owner", "admin", "member"},
    "update": lambda u, inv, role: (
        role in {"owner", "admin"}
        or (role == "member" and inv.created_by_id == u.id
            and inv.status == "draft")
    ),
    "delete": lambda u, inv, role: (
        role in {"owner", "admin"} and inv.status != "paid"
    ),
    "export": lambda u, inv, role: role in {"owner", "admin"},
}

def can(user, action, invoice):
    role = get_role(user.id, invoice.organization_id)  # from DB
    rule = RULES.get(action)
    if rule is None:
        return False          # unknown action: deny
    return bool(rule(user, invoice, role))

If you already use a policy library (Pundit in Rails, django-rules or django-guardian, CASL in JavaScript, or a policy engine such as Open Policy Agent or Cedar), tell the model which one and paste an existing policy so it follows the same shape. Do not let it invent a second, parallel permission system next to the one you have.

Step 4: Scope queries, do not just check after loading

A permission function is necessary but not sufficient. List endpoints, search, exports, and counts do not load one object you can check; they run a query. The safest pattern is to make the tenant or owner part of every query, so a forgotten check returns nothing instead of everything:

# Risky: loads any invoice, relies on a later check
invoice = Invoice.objects.get(id=invoice_id)

# Safer: the query itself is limited to the user's organizations
invoice = Invoice.objects.get(
    id=invoice_id,
    organization__memberships__user=request.user,
)

When a scoped lookup finds nothing, return 404 rather than 403 for resources the user should not know exist. That stops people from probing which IDs are valid. Ask the model explicitly: "Every query that touches Invoice must filter by the current user's organizations. Show me any query in this file that does not."

A wooden hotel key rack with numbered slots

A hotel guest gets the key to their own room, not the whole rack. Scope every query the same way. Image: Belmont Hotel Wooden Key Rack by Nan Palmero from San Antonio, TX, USA, CC BY 2.0, via Wikimedia Commons.

Step 5: Never trust ownership fields from the client

Generated create and update handlers often copy the whole request body into the model. That is how users assign records to other accounts or grant themselves roles (sometimes called mass assignment). Tell the model to use an allowlist of editable fields and to set ownership on the server:

ALLOWED_UPDATE_FIELDS = {"title", "due_date", "line_items", "notes"}

data = {k: v for k, v in request.json.items()
        if k in ALLOWED_UPDATE_FIELDS}
invoice.update(**data)

# On create, ownership comes from the session, not the body
invoice = Invoice.create(**data,
                         organization_id=current_org.id,
                         created_by_id=request.user.id)

Fields like organization_id, created_by_id, role, status (when status changes need their own permission), and anything named is_admin should never come from user input on a general update route.

Step 6: Test as the wrong user

Most test suites only test the happy path: the owner reads their own invoice. Authorization bugs live in the other cells of the table. Build a small fixture with at least two organizations and one user per role, then generate a test for every row of your permission table, including the denials.

This is a good job for an LLM, because it is repetitive and the spec is already written. Prompt:

Using this permission table and these fixtures (org A, org B,
users: ownerA, adminA, memberA, viewerA, ownerB), write
parametrized pytest tests that call the real HTTP endpoints.
For every action and every user, assert the exact expected status
code. Include: a user from org B accessing org A's invoice,
a member editing another member's draft, deleting a paid invoice,
and an unknown action.

A parametrized test keeps the matrix readable:

@pytest.mark.parametrize("user, method, path, expected", [
    ("ownerA",  "GET",    "/invoices/{a_inv}", 200),
    ("viewerA", "GET",    "/invoices/{a_inv}", 200),
    ("ownerB",  "GET",    "/invoices/{a_inv}", 404),  # other tenant
    ("viewerA", "DELETE", "/invoices/{a_inv}", 403),
    ("memberA", "PATCH",  "/invoices/{other_draft}", 403),
    ("adminA",  "DELETE", "/invoices/{paid_inv}", 403),
])
def test_invoice_access(client, fixtures, user, method, path, expected):
    resp = client.as_user(fixtures[user]).request(
        method, path.format(**fixtures.ids))
    assert resp.status_code == expected

Run the tests, then do one sanity check that is easy to skip: temporarily break a rule (for example, make delete return True for everyone) and confirm the suite goes red. If it stays green, the tests are not actually exercising the check.

Step 7: Audit every route, not just the new one

Once you have a central can() function, ask the model to help you find routes that do not call it. Paste your route list or router file and ask for a table: route, HTTP method, resource touched, permission check used (or "none"). Then verify the "none" rows yourself. Common misses are export and download endpoints, admin-only JSON endpoints that power internal dashboards, GraphQL resolvers for nested fields, and background jobs triggered by a user-supplied ID.

For a lasting guard, add a test that enumerates registered routes and fails if a new route is added without either a permission decorator or an explicit "public" marker. That turns "remember to add a check" into something CI enforces.

A short checklist before you merge

  1. There is a written permission table, and the code matches it.
  2. All decisions go through one function or policy layer, and unknown actions are denied.
  3. Every query on tenant data is scoped to the current user's tenant or ownership.
  4. Roles, owners, and tenant IDs are set on the server, never copied from the request.
  5. The API enforces the rules even if the UI hides the button.
  6. Tests cover denials, cross-tenant access, and state-based rules, and they fail when a rule is broken on purpose.
  7. Every route has been checked, including exports, bulk actions, and background jobs.

The takeaway

LLMs are good at the mechanical parts of authorization: turning a clear rule table into code, scoping queries consistently, and generating the tedious matrix of tests. They are bad at inventing your business rules, and they will not add checks you never asked for. Write the rules first, deny by default, scope every query, and test as the user who should be turned away. That last step is the one that actually proves the door is locked.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Tencent Hy4 Preview: Open 770B MoE Built for Real Work

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)