Programming Search⌘K

Weaknesscore

Missing authorization

Also called missing authorization check, missing access control, insecure direct object reference, IDOR, broken object level authorization, BOLA, missing function level access control, cwe-862.

Missing authorization happens when a program checks who the user is but not whether that user may do the action or reach the object, so a changed id or URL gives access.

Abstraction
class
OWASP Top 10 (2025)
A01
CWE Top 25 (2025)
rank 4
Languages affected
any

Description

Authentication answers the question "who is this user?". Authorization answers the question "may this user do this action on this object?". CWE calls the two AuthN and AuthZ. It discourages the short form "Auth", because it could mean either one.1 Missing authorization happens when the product does not perform an authorization check when an actor attempts to access a resource or perform an action.1 The user is often logged in. The program knows who the user is, but it never asks whether that user may do what the request asks.

The weakness has two common forms:

  • Function level. A normal user calls a function for administrators, such as a page that resets a password. The page may have no link for normal users, but the server answers a direct request. CWE-425, Direct Request, is a child of CWE-862 for this case.1
  • Object level. A user changes the identifier of a record in a request, and the server returns the record of another user. CWE-639 describes this case. The product does not prevent one user from gaining access to another user's data by modifying the key value.2 Its alternate terms are insecure direct object reference (IDOR), broken object level authorization (BOLA) and horizontal authorization.2

CWE gives two examples. In the first, a function uses a prepared statement, so it is safe from SQL injection. But it never checks that the user may run the query.1 In the second, a message board checks the password, and then it shows any private message whose id the user sends.1 An attacker can read or change data, gain privileges, or use up resources until the service stops.1

CWE notes two ways that the weakness starts. A single-user application moves to a multi-user environment. Or a developer assumes that attackers cannot change inputs such as headers or cookies.1 The OWASP Authorization Cheat Sheet says that permission should be validated correctly on every request. It adds that an attacker only needs to find one way in.5

CWE-862 is a class weakness. It is a child of CWE-285, Improper Authorization. Its children include CWE-425 and CWE-638, Not Using Complete Mediation.1 It is rank 4 on the 2025 CWE Top 25, up from rank 9 the year before.3 On the same list, CWE-863, Incorrect Authorization, is rank 17, and CWE-639 is rank 24.3 The OWASP Top 10:2025 maps all three to A01:2025 Broken Access Control. That category lists IDOR as viewing or editing someone else's account by providing its unique identifier.4

Cross-site request forgery is a different weakness. There the check is present, and the attacker makes the browser of an authorized user send the request.

History

Saltzer and Schroeder stated the two principles behind the fix in 1975.6 Complete mediation says: "Every access to every object must be checked for authority."6 Fail-safe defaults says: "Base access decisions on permission rather than exclusion."6 They credit the second principle to E. Glaser in 1965. They warn that a mechanism that lists exclusions tends to fail by allowing access, and that this failure may go unnoticed in normal use.6

The OWASP Top Ten 2007 had a category A4, Insecure Direct Object Reference. The 2019 OWASP API Security Top 10 used the name BOLA.2 CWE-862 entered CWE in version 1.13, released on 2011-06-01.1

Vulnerable code

The handlers below check that the caller is logged in. They never check what the caller may do. Dictionaries stand for the session store and the database. The classic demonstration is to change the id in the URL from 1 to 2.

This code runs but gives a wrong answer on purpose.

# Sessions and records stand in for a real session store and database.
SESSIONS = {"session-alice": "alice", "session-bob": "bob"}
INVOICES = {
    1: {"owner": "alice", "total": 120},
    2: {"owner": "bob", "total": 75},
}
USERS = {"alice", "bob"}


def get_invoice(session, invoice_id):
    user = SESSIONS.get(session)
    if user is None:
        return 401, "log in first"
    invoice = INVOICES.get(invoice_id)
    if invoice is None:
        return 404, "not found"
    # Missing: a check that the invoice belongs to user.
    return 200, invoice


def delete_user(session, name):
    if SESSIONS.get(session) is None:
        return 401, "log in first"
    # Missing: a check that the caller is an administrator.
    USERS.discard(name)
    return 200, f"deleted {name}"


# Alice opens her own invoice. Then she changes the id in the URL from 1 to 2.
print(get_invoice("session-alice", 1))
print(get_invoice("session-alice", 2))
# Alice is not an administrator, but the handler deletes bob.
print(delete_user("session-alice", "bob"))
Output
(200, {'owner': 'alice', 'total': 120})
(200, {'owner': 'bob', 'total': 75})
(200, 'deleted bob')

The second call gives Bob's invoice to Alice. The third call lets a customer delete a user. Both handlers authenticate the caller, but neither one authorizes the action.

Fixed code

The fix puts one check in front of every handler. Each route names the permission that it needs, and a policy lists the permissions of each role. The invoice lookup also includes the owner.

SESSIONS = {"session-alice": "alice", "session-carol": "carol"}
ROLES = {"alice": "customer", "bob": "customer", "carol": "admin"}
# The policy lists what each role may do. Anything not listed is denied.
POLICY = {
    "customer": {"invoice:read"},
    "admin": {"invoice:read", "user:delete"},
}
INVOICES = {
    1: {"owner": "alice", "total": 120},
    2: {"owner": "bob", "total": 75},
}
USERS = {"alice", "bob", "carol"}
ROUTES = {}


def route(name, *, permission):
    """Register a handler. permission has no default value."""
    def register(handler):
        ROUTES[name] = (permission, handler)
        return handler
    return register


def allowed(user, permission):
    return permission in POLICY.get(ROLES.get(user), set())


def dispatch(name, session, *args):
    """Every request passes through this one check."""
    if name not in ROUTES:
        return 404, "not found"
    permission, handler = ROUTES[name]
    user = SESSIONS.get(session)
    if user is None:
        return 401, "log in first"
    if not allowed(user, permission):
        return 403, "forbidden"
    return handler(user, *args)


def invoices_of(user):
    # In SQL: SELECT ... FROM invoices WHERE owner = ?
    return {k: v for k, v in INVOICES.items() if v["owner"] == user}


@route("get_invoice", permission="invoice:read")
def get_invoice(user, invoice_id):
    invoice = invoices_of(user).get(invoice_id)
    if invoice is None:
        return 404, "not found"
    return 200, invoice


@route("delete_user", permission="user:delete")
def delete_user(user, name):
    USERS.discard(name)
    return 200, f"deleted {name}"


print(dispatch("get_invoice", "session-alice", 1))
print(dispatch("get_invoice", "session-alice", 2))
print(dispatch("delete_user", "session-alice", "bob"))
print(dispatch("delete_user", "session-carol", "bob"))
print(dispatch("get_invoice", "no-such-session", 1))

# A route without a permission does not register.
try:
    @route("export_all")
    def export_all(user):
        return 200, INVOICES
except TypeError as error:
    print("refused:", error)
Output
(200, {'owner': 'alice', 'total': 120})
(404, 'not found')
(403, 'forbidden')
(200, 'deleted bob')
(401, 'log in first')
refused: route() missing 1 required keyword-only argument: 'permission'

Alice reads invoice 1 and gets 404 for invoice 2. She gets 403 when she tries to delete a user, and Carol, an administrator, can do it. A request without a session gets 401. The last line shows that a route without a permission does not register, because permission has no default value.

Deny by default

The policy lists only what each role may do. A user without a role, a role that is not in the policy, and a permission that no role has all get 403. This is the deny-by-default rule. The OWASP Top 10:2025 says: "Except for public resources, deny by default."4 The Authorization Cheat Sheet asks developers to justify each permission, and not to assume that access is the default.5

A list of forbidden actions fails in the other direction. A developer adds a route and forgets to add it to the list, and the route is open to everyone.

Check the object, not only the role

A role check does not stop one customer from reading the invoice of another customer, because both have the same role. CWE says that role-based access control may not protect against horizontal authorization.1 So the fixed code scopes the lookup to the user. The OWASP IDOR Prevention Cheat Sheet says to look up objects in datasets that the user has access to.7 In SQL, put the owner in the WHERE clause, as in WHERE id = ? AND owner = ?. The OWASP API Security Top 10 asks for the check in every function that reads a record with an input from the client.8

The fixed handler returns 404 for another user's invoice. This is the same answer as for an invoice that does not exist, so the response does not tell the caller which ids exist.

Random identifiers, such as UUIDs, make ids hard to guess. They do not replace the check. The IDOR cheat sheet says that access control checks are essential even with complex identifiers. If attackers obtain the URL of an object, the application must still block them.7

Where the check goes

Put the check on the server. The Authorization Cheat Sheet says that developers must never rely on client-side access control checks.5 A hidden button does not stop a direct request. Put the check in one place that every request passes through, such as a middleware or a dispatcher. The OWASP Top 10:2025 says to implement access control mechanisms once and reuse them throughout the application.4 Frameworks have such a place. In ASP.NET MVC, the Authorize attribute requires authorization on an action method.9 The cheat sheet also prefers explicit configuration, even when a framework denies by default.5

How to detect it

  • Tests with two users. The IDOR cheat sheet says to create User A and User B, and objects for each one. Then log in as User A and try to reach the objects of User B.7 Test reads, creates, updates, deletes, exports and administrative actions.7 The API Security Top 10 says not to deploy changes that make these tests fail.8 The Authorization Cheat Sheet also asks for unit and integration tests of the authorization logic.5
  • A route inventory. List every route with its permission. A test that fails on a route without a permission finds the gap before release. The examples make the permission a required argument for the same reason.
  • Static analysis. CWE rates automated static analysis as limited here. Tools have difficulty with custom authorization schemes, and some functions are public by design.1 CodeQL for C# has the queries cs/web/missing-function-level-access-control9 and cs/web/insecure-direct-object-reference.10
  • Manual review. CWE rates manual analysis as moderate, and architecture or design review as highly effective.1 For each handler, ask who the caller is and whether the caller may do this action to this object.
  • Dynamic scanners. They can find interfaces that do not require authorization. A person must still decide whether each one breaks the business rules.1

How to prevent it

  • Deny by default. Grant each permission on purpose, and refuse everything else.45
  • Check every request on the server. Do not trust the client to hide or block an action.56
  • Implement the check once. Use one middleware, dispatcher or framework attribute, and make routes declare their permission.4
  • Scope data access to the user. Look up records through the owner or the tenant, not by id alone.7
  • Map roles to areas. CWE suggests anonymous, normal, privileged and administrative areas, with role-based access control at the boundaries.1
  • Check business rules. A database may limit medical records to one database user. CWE notes that each record may still be meant only for the patient and the doctor.1
  • Log failures. The OWASP Top 10:2025 says to log access control failures and alert admins when appropriate.4

Real cases

Case Date What happened
CVE-2009-2213 published 2009-06-25 The default configuration of the Citrix NetScaler Access Gateway set the Default Authorization Action to Allow. Authenticated users might bypass the intended access restrictions.11
CVE-2009-3168 published 2009-09-11 Basic PHP Events Lister 2.0 did not restrict access to two admin scripts. Authenticated users could reset administrator passwords or add administrators with a direct request.12
CVE-2021-36539 published 2023-01-26 Instructure Canvas LMS did not deny access to locked or unpublished files through the file preview URL.13 CWE lists it under CWE-639, because file ids were not restricted to the user.2
CVE-2024-6845 published 2024-09-25 A REST endpoint of the Chatbot with ChatGPT WordPress plugin, before 2.4.6, had no proper authorization. Unauthenticated users could get the encoded OpenAI API key and decode it.14
PythonGitHub

This code runs but gives a wrong answer on purpose.

# Sessions and records stand in for a real session store and database.
SESSIONS = {"session-alice": "alice", "session-bob": "bob"}
INVOICES = {
    1: {"owner": "alice", "total": 120},
    2: {"owner": "bob", "total": 75},
}
USERS = {"alice", "bob"}


def get_invoice(session, invoice_id):
    user = SESSIONS.get(session)
    if user is None:
        return 401, "log in first"
    invoice = INVOICES.get(invoice_id)
    if invoice is None:
        return 404, "not found"
    # Missing: a check that the invoice belongs to user.
    return 200, invoice


def delete_user(session, name):
    if SESSIONS.get(session) is None:
        return 401, "log in first"
    # Missing: a check that the caller is an administrator.
    USERS.discard(name)
    return 200, f"deleted {name}"


# Alice opens her own invoice. Then she changes the id in the URL from 1 to 2.
print(get_invoice("session-alice", 1))
print(get_invoice("session-alice", 2))
# Alice is not an administrator, but the handler deletes bob.
print(delete_user("session-alice", "bob"))
Output
(200, {'owner': 'alice', 'total': 120})
(200, {'owner': 'bob', 'total': 75})
(200, 'deleted bob')

The handlers check the session and nothing else. Alice gets Bob's invoice when she changes the id from 1 to 2, and a customer deletes a user.

SESSIONS = {"session-alice": "alice", "session-carol": "carol"}
ROLES = {"alice": "customer", "bob": "customer", "carol": "admin"}
# The policy lists what each role may do. Anything not listed is denied.
POLICY = {
    "customer": {"invoice:read"},
    "admin": {"invoice:read", "user:delete"},
}
INVOICES = {
    1: {"owner": "alice", "total": 120},
    2: {"owner": "bob", "total": 75},
}
USERS = {"alice", "bob", "carol"}
ROUTES = {}


def route(name, *, permission):
    """Register a handler. permission has no default value."""
    def register(handler):
        ROUTES[name] = (permission, handler)
        return handler
    return register


def allowed(user, permission):
    return permission in POLICY.get(ROLES.get(user), set())


def dispatch(name, session, *args):
    """Every request passes through this one check."""
    if name not in ROUTES:
        return 404, "not found"
    permission, handler = ROUTES[name]
    user = SESSIONS.get(session)
    if user is None:
        return 401, "log in first"
    if not allowed(user, permission):
        return 403, "forbidden"
    return handler(user, *args)


def invoices_of(user):
    # In SQL: SELECT ... FROM invoices WHERE owner = ?
    return {k: v for k, v in INVOICES.items() if v["owner"] == user}


@route("get_invoice", permission="invoice:read")
def get_invoice(user, invoice_id):
    invoice = invoices_of(user).get(invoice_id)
    if invoice is None:
        return 404, "not found"
    return 200, invoice


@route("delete_user", permission="user:delete")
def delete_user(user, name):
    USERS.discard(name)
    return 200, f"deleted {name}"


print(dispatch("get_invoice", "session-alice", 1))
print(dispatch("get_invoice", "session-alice", 2))
print(dispatch("delete_user", "session-alice", "bob"))
print(dispatch("delete_user", "session-carol", "bob"))
print(dispatch("get_invoice", "no-such-session", 1))

# A route without a permission does not register.
try:
    @route("export_all")
    def export_all(user):
        return 200, INVOICES
except TypeError as error:
    print("refused:", error)
Output
(200, {'owner': 'alice', 'total': 120})
(404, 'not found')
(403, 'forbidden')
(200, 'deleted bob')
(401, 'log in first')
refused: route() missing 1 required keyword-only argument: 'permission'

dispatch is the one place where every request is checked. invoices_of scopes the lookup to the caller, so another user's invoice gives the same 404 as a missing one.

  • Verdict: stdlib. Python has no web authorization in the standard library. The check is a plain function, and web frameworks give the same hook as a decorator or a middleware.
  • A required keyword-only argument, such as permission in route, makes Python refuse a route that has no permission. A default value such as permission=None would bring the gap back.
  • With an SQL database, write the scope into the query: SELECT ... FROM invoices WHERE id = ? AND owner = ?. Pass both values as parameters, as SQL injection shows.
JavaGitHub
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;

public class Main {
    enum Permission { INVOICE_READ, USER_DELETE }

    record Invoice(int id, String owner, int total) {}

    record Response(int status, String body) {}

    static final Map<String, String> SESSIONS = Map.of("session-alice", "alice", "session-carol", "carol");
    static final Map<String, String> ROLES = Map.of("alice", "customer", "bob", "customer", "carol", "admin");
    // The policy lists what each role may do. Anything not listed is denied.
    static final Map<String, Set<Permission>> POLICY = Map.of(
            "customer", Set.of(Permission.INVOICE_READ),
            "admin", Set.of(Permission.INVOICE_READ, Permission.USER_DELETE));
    static final List<Invoice> INVOICES = List.of(new Invoice(1, "alice", 120), new Invoice(2, "bob", 75));

    interface Handler { Response handle(String user, String arg); }

    // A route cannot exist without a permission.
    record Route(Permission permission, Handler handler) {
        Route {
            Objects.requireNonNull(permission, "permission");
        }
    }

    // In SQL: SELECT ... FROM invoices WHERE id = ? AND owner = ?
    static Optional<Invoice> findByIdAndOwner(int id, String owner) {
        return INVOICES.stream().filter(i -> i.id() == id && i.owner().equals(owner)).findFirst();
    }

    static final Map<String, Route> ROUTES = Map.of(
            "getInvoice", new Route(Permission.INVOICE_READ, (user, arg) -> findByIdAndOwner(Integer.parseInt(arg), user)
                    .map(i -> new Response(200, i.toString()))
                    .orElse(new Response(404, "not found"))),
            "deleteUser", new Route(Permission.USER_DELETE, (user, arg) -> new Response(200, "deleted " + arg)));

    // Every request passes through this one check.
    static Response dispatch(String name, String session, String arg) {
        Route route = ROUTES.get(name);
        if (route == null) return new Response(404, "not found");
        String user = SESSIONS.get(session);
        if (user == null) return new Response(401, "log in first");
        Set<Permission> granted = POLICY.getOrDefault(ROLES.get(user), Set.of());
        if (!granted.contains(route.permission())) return new Response(403, "forbidden");
        return route.handler().handle(user, arg);
    }

    public static void main(String[] args) {
        System.out.println(dispatch("getInvoice", "session-alice", "1"));
        System.out.println(dispatch("getInvoice", "session-alice", "2"));
        System.out.println(dispatch("deleteUser", "session-alice", "bob"));
        System.out.println(dispatch("deleteUser", "session-carol", "bob"));
        System.out.println(dispatch("getInvoice", "none", "1"));
        try {
            new Route(null, (user, arg) -> new Response(200, "all invoices"));
        } catch (NullPointerException e) {
            System.out.println("refused: " + e.getMessage());
        }
    }
}
Output
Response[status=200, body=Invoice[id=1, owner=alice, total=120]]
Response[status=404, body=not found]
Response[status=403, body=forbidden]
Response[status=200, body=deleted bob]
Response[status=401, body=log in first]
refused: permission

The compact constructor of Route refuses a null permission, so a route cannot exist without one. findByIdAndOwner takes the owner as a parameter, so a handler cannot look up an invoice by id alone.

  • Verdict: stdlib. Java SE has no web authorization. Jakarta EE and Spring add annotations and filters for the check.
  • An enum for permissions makes a typing mistake a compile error. A string permission with a typing mistake fails closed here, because no role holds it.
  • Name repository methods after their scope, such as findByIdAndOwner, so that a review sees a lookup by id alone.
var sessions = new Dictionary<string, string> { ["session-alice"] = "alice", ["session-carol"] = "carol" };
var roles = new Dictionary<string, string> { ["alice"] = "customer", ["bob"] = "customer", ["carol"] = "admin" };
// The policy lists what each role may do. Anything not listed is denied.
var policy = new Dictionary<string, HashSet<Permission>>
{
    ["customer"] = [Permission.InvoiceRead],
    ["admin"] = [Permission.InvoiceRead, Permission.UserDelete],
};
Invoice[] invoices = [new(1, "alice", 120), new(2, "bob", 75)];

var routes = new Dictionary<string, Route>
{
    ["getInvoice"] = new(Permission.InvoiceRead, (user, arg) =>
    {
        // In SQL: SELECT ... FROM invoices WHERE id = @id AND owner = @user
        var invoice = invoices.FirstOrDefault(i => i.Id == int.Parse(arg) && i.Owner == user);
        return invoice is null ? (404, "not found") : (200, invoice.ToString());
    }),
    ["deleteUser"] = new(Permission.UserDelete, (user, arg) => (200, $"deleted {arg}")),
};

// Every request passes through this one check.
(int, string) Dispatch(string name, string session, string arg)
{
    if (!routes.TryGetValue(name, out var route)) return (404, "not found");
    if (!sessions.TryGetValue(session, out var user)) return (401, "log in first");
    var granted = roles.TryGetValue(user, out var role) && policy.TryGetValue(role, out var set) && set.Contains(route.Permission);
    if (!granted) return (403, "forbidden");
    return route.Handler(user, arg);
}

Console.WriteLine(Dispatch("getInvoice", "session-alice", "1"));
Console.WriteLine(Dispatch("getInvoice", "session-alice", "2"));
Console.WriteLine(Dispatch("deleteUser", "session-alice", "bob"));
Console.WriteLine(Dispatch("deleteUser", "session-carol", "bob"));
Console.WriteLine(Dispatch("getInvoice", "none", "1"));

// None is the default value of the enum, and no role has it.
enum Permission { None, InvoiceRead, UserDelete }

record Invoice(int Id, string Owner, int Total);

// The constructor needs a permission, so a route cannot exist without one.
record Route(Permission Permission, Func<string, string, (int, string)> Handler);
Output
(200, Invoice { Id = 1, Owner = alice, Total = 120 })
(404, not found)
(403, forbidden)
(200, deleted bob)
(401, log in first)

Dispatch checks the session and the policy before it calls a handler. The getInvoice handler matches the id and the owner together.

  • Verdict: stdlib. In ASP.NET Core, the Authorize attribute and authorization policies give the same check. CodeQL has queries for a missing check and for direct object references in C# web code.
  • Permission.None is the default value of the enum. A route built with default gets None, and no role has it, so the route is denied.
  • In Entity Framework, add the owner to the query, as in Where(i => i.Id == id && i.Owner == user).
JavaScriptGitHub
const sessions = new Map([["session-alice", "alice"], ["session-carol", "carol"]]);
const roles = new Map([["alice", "customer"], ["bob", "customer"], ["carol", "admin"]]);
// The policy lists what each role may do. Anything not listed is denied.
const policy = new Map([
  ["customer", new Set(["invoice:read"])],
  ["admin", new Set(["invoice:read", "user:delete"])],
]);
const invoices = [
  { id: 1, owner: "alice", total: 120 },
  { id: 2, owner: "bob", total: 75 },
];

const routes = new Map();

function route(name, { permission, handler }) {
  if (typeof permission !== "string") {
    throw new Error(`route ${name} has no permission`);
  }
  routes.set(name, { permission, handler });
}

// Every request passes through this one check.
function dispatch(name, session, ...args) {
  const entry = routes.get(name);
  if (!entry) return [404, "not found"];
  const user = sessions.get(session);
  if (user === undefined) return [401, "log in first"];
  if (!(policy.get(roles.get(user))?.has(entry.permission) ?? false)) {
    return [403, "forbidden"];
  }
  return entry.handler(user, ...args);
}

route("getInvoice", {
  permission: "invoice:read",
  handler(user, id) {
    // The lookup includes the owner, as WHERE id = ? AND owner = ? does.
    const invoice = invoices.find((i) => i.id === id && i.owner === user);
    return invoice ? [200, invoice] : [404, "not found"];
  },
});

route("deleteUser", {
  permission: "user:delete",
  handler: (user, name) => [200, `deleted ${name}`],
});

console.log(dispatch("getInvoice", "session-alice", 1));
console.log(dispatch("getInvoice", "session-alice", 2));
console.log(dispatch("deleteUser", "session-alice", "bob"));
console.log(dispatch("deleteUser", "session-carol", "bob"));
console.log(dispatch("getInvoice", "none", 1));

try {
  route("exportAll", { handler: () => [200, invoices] });
} catch (error) {
  console.log("refused:", error.message);
}
Output
[ 200, { id: 1, owner: 'alice', total: 120 } ]
[ 404, 'not found' ]
[ 403, 'forbidden' ]
[ 200, 'deleted bob' ]
[ 401, 'log in first' ]
refused: route exportAll has no permission

route throws when a route has no permission, and dispatch checks the session and the policy before any handler runs. The invoice lookup matches the id and the owner together.

  • Verdict: stdlib. Node.js has no authorization layer. Web frameworks add the same check as middleware.
  • The expression policy.get(roles.get(user))?.has(entry.permission) ?? false denies by default. A user with no role, or a role with no entry, gives false.
  • A check in browser code only changes what the page shows. The server must repeat every check.
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
)

type invoice struct {
	Owner string
	Total int
}

var (
	sessions = map[string]string{"session-alice": "alice", "session-carol": "carol"}
	roles    = map[string]string{"alice": "customer", "bob": "customer", "carol": "admin"}
	// policy lists what each role may do. Anything not listed is denied.
	policy = map[string]map[string]bool{
		"customer": {"invoice:read": true},
		"admin":    {"invoice:read": true, "user:delete": true},
	}
	invoices = map[int]invoice{1: {"alice", 120}, 2: {"bob", 75}}
)

type userHandler func(w http.ResponseWriter, r *http.Request, user string)

// handle registers a route only together with the permission that it needs.
func handle(mux *http.ServeMux, pattern, permission string, h userHandler) {
	mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
		user, ok := "", false
		if c, err := r.Cookie("session"); err == nil {
			user, ok = sessions[c.Value]
		}
		if !ok {
			http.Error(w, "log in first", http.StatusUnauthorized)
			return
		}
		if !policy[roles[user]][permission] {
			http.Error(w, "forbidden", http.StatusForbidden)
			return
		}
		h(w, r, user)
	})
}

func getInvoice(w http.ResponseWriter, r *http.Request, user string) {
	id, err := strconv.Atoi(r.PathValue("id"))
	inv, ok := invoices[id]
	// Another user's invoice gets the same answer as a missing one.
	if err != nil || !ok || inv.Owner != user {
		http.NotFound(w, r)
		return
	}
	fmt.Fprintf(w, "invoice %d total %d", id, inv.Total)
}

func deleteUser(w http.ResponseWriter, r *http.Request, user string) {
	fmt.Fprintf(w, "deleted %s", r.PathValue("name"))
}

func main() {
	mux := http.NewServeMux()
	handle(mux, "GET /invoices/{id}", "invoice:read", getInvoice)
	handle(mux, "DELETE /users/{name}", "user:delete", deleteUser)

	// httptest calls the handler in memory. Nothing goes over the network.
	send := func(method, path, session string) {
		req := httptest.NewRequest(method, path, nil)
		req.AddCookie(&http.Cookie{Name: "session", Value: session})
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, req)
		fmt.Printf("%-6s %-15s %-14s %d %s\n", method, path, session, rec.Code, strings.TrimSpace(rec.Body.String()))
	}
	send("GET", "/invoices/1", "session-alice")
	send("GET", "/invoices/2", "session-alice")
	send("DELETE", "/users/bob", "session-alice")
	send("DELETE", "/users/bob", "session-carol")
	send("GET", "/invoices/1", "none")
}
Output
GET    /invoices/1     session-alice  200 invoice 1 total 120
GET    /invoices/2     session-alice  404 404 page not found
DELETE /users/bob      session-alice  403 forbidden
DELETE /users/bob      session-carol  200 deleted bob
GET    /invoices/1     none           401 log in first

handle is the only way to add a route, and it takes the permission as an argument. The handler runs only after the check passes. getInvoice compares the owner with the caller, and answers 404 for another user's invoice.

  • Verdict: stdlib. net/http has no authorization, but a function that wraps a handler is the usual place for the check. httptest runs the handlers in memory, with no network.
  • Method and wildcard patterns such as GET /invoices/{id} and r.PathValue need Go 1.22 or later.
  • A route that someone adds with mux.HandleFunc directly skips the check. Review for such calls, or keep the ServeMux unexported behind handle.

References

  1. CWE-862: Missing Authorization, Description; Alternate Terms; Common Consequences; Potential Mitigations; Relationships; Modes Of Introduction; Demonstrative Examples, Examples 1 and 2; Observed Examples; Detection Methods; Content History
  2. CWE-639: Authorization Bypass Through User-Controlled Key, Description; Alternate Terms; Observed Examples; Memberships
  3. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 4, Rank Last Year; ranks 17 and 24
  4. OWASP Top 10:2025, A01:2025 Broken Access Control, Description; How to prevent; List of Mapped CWEs
  5. OWASP Cheat Sheet Series, Authorization Cheat Sheet, Deny by Default; Validate the Permissions on Every Request; Verify that Authorization Checks are Performed in the Right Location; Create Unit and Integration Test Cases for Authorization Logic
  6. Jerome H. Saltzer and Michael D. Schroeder, The Protection of Information in Computer Systems, Proceedings of the IEEE 63(9), 1975, pages 1278 to 1308, Section I.A.3, Design Principles, b) Fail-safe defaults and c) Complete mediation
  7. OWASP Cheat Sheet Series, Insecure Direct Object Reference Prevention Cheat Sheet, Identifier complexity; Verifying access controls; Mitigation
  8. OWASP API Security Top 10 2023, API1:2023 Broken Object Level Authorization, How To Prevent
  9. CodeQL query help for C#, Missing function level access control, the query ID; Recommendation
  10. CodeQL query help for C#, Insecure Direct Object Reference, the query ID; Recommendation
  11. CVE-2009-2213, Citrix NetScaler Access Gateway, the description and the publication date
  12. CVE-2009-3168, Basic PHP Events Lister, the description and the publication date
  13. CVE-2021-36539, Instructure Canvas LMS, the description and the publication date
  14. CVE-2024-6845, Chatbot with ChatGPT WordPress plugin, the description and the publication date

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/3A0889/text.yaml