Skip to content

Broken function-level authorization (roles and permissions)

When is it relevant

A new or changed entry point that should be limited to certain roles or permissions: admin actions, settings, user and role management, billing, key or token management. Also a change to how roles and permissions are assigned or evaluated.

Attack

A lower-privileged user calls the privileged endpoint directly, because the restriction exists only in the UI. Other variants:

  • Sibling routes check a permission but the new one doesn't.
  • The route checks a different permission from the action it performs.
  • A user grants themselves, or others, a role more powerful than their own.

Mitigation

  • Put an explicit permission check on every privileged route, and deny by default.
  • Check the permission for the exact action performed, and keep it consistent across siblings (GET, POST, DELETE).
  • Enforce a delegation ceiling: a user can only grant roles or permissions they already hold.
  • Never trust a role or permission sent by the client.

Test

  • Point-in-time: call every privileged route with the token of a role that shouldn't have it. Each must return 403, including the sibling methods (GET, POST, DELETE) of the same resource.
  • Continuous: a role-by-route matrix test (role × route → expected status) that runs in CI. A role that grants a role above its own is one of the rows.

Examples

Mitigation options

Option When it fits Docs
Router-level middleware A whole area is one privilege level (/admin/*) Express routing
Per-route middleware Mixed privileges inside one router; explicit per endpoint Express routing
Policy/ability layer Rules are data, reused by API and UI CASL

Vulnerable — the check the UI does, the API doesn't

router.get('/admin/users', requireAuth, async (req, res) => {
  res.json(await User.find())          // any logged-in user reaches this
})

Vulnerable — one sibling forgotten

router.get('/courses/:id',    requireAuth, requireTeacher, getCourse)
router.put('/courses/:id',    requireAuth, requireTeacher, updateCourse)
router.delete('/courses/:id', requireAuth,                 deleteCourse)  // gap

Mitigated — router-level middleware

const admin = express.Router()
admin.use(requireAuth, requireRole('admin'))   // applies to every route below

admin.get('/users', async (req, res) => res.json(await User.find()))
admin.delete('/users/:id', async (req, res) => { /* ... */ })

app.use('/admin', admin)

Mounting the middleware on the router means a new route added later is covered by default, which is why a forgotten sibling is less likely than with per-route checks.

Mitigated — per-route middleware

function requireRole(...allowed) {
  return (req, res, next) => {
    const role = req.user?.role                 // from the session, not the body
    if (!allowed.includes(role)) return res.sendStatus(403)
    next()
  }
}

router.delete('/courses/:id', requireAuth, requireRole('teacher', 'admin'), deleteCourse)

Mitigated — policy layer

const ability = defineAbilityFor(req.user)
if (ability.cannot('delete', course)) return res.sendStatus(403)

Docs: CASL

Bypasses to check

  • Check then change the value. The guard and the use read the role differently:
if (req.body.role === 'admin') return res.sendStatus(403)   // reject admins
await User.create({ ...req.body, role: req.body.role.toLowerCase() })

"Admin", " admin" and "ADMİN" (dotted capital I, which lowercases to i̇) all pass the guard, and trimming or normalize('NFKC') afterwards can turn the stored value back into admin. Normalise once, before the check, then use that same normalised value. - Role read from the request (req.body.role, X-Role) or from an unverified JWT claim instead of from the server-side session. - Middleware registered after the route it is meant to protect, or app.use(requireAuth) placed below app.use('/api', routes). - Method not covered: a guard on router.get while router.post, patch or delete on the same path is unguarded; router.all vs one verb. - Path shape differences that skip a mount: trailing slash, %2e%2e, double slashes, or case (/Admin/users) when the guard is mounted on /admin. - Internal or "service" routes that skip auth because they are assumed to be unreachable from the internet. - The check returns but doesn't stop: if (!ok) res.sendStatus(403) without return, so the handler keeps running.

What to grep for

  • requireAuth, requireRole, isAdmin, req.user.role, req.session.role
  • router.use(, app.use(, router.all(
  • next() called unconditionally inside a guard

Mitigation options

Option When it fits Docs
URL rules in the SecurityFilterChain A whole area is one privilege level (/admin/**) Authorize HTTP requests
Method security (@PreAuthorize) Mixed privileges in one controller; the rule sits on the method Method security
Service-layer check against the resource's role Roles are per resource (project admin, org owner), not global @PreAuthorize with beans

Global roles (ROLE_ADMIN) and per-resource roles (owner or admin of this project) need different tools. URL rules and hasRole only see the global authorities on the Authentication; a per-project role has to be checked in code, or in a @PreAuthorize that calls a bean.

Vulnerable — annotations that never run

@SpringBootApplication                       // no @EnableMethodSecurity anywhere
public class App { }

@RestController
class UserAdminController {
    @PreAuthorize("hasRole('ADMIN')")         // silently ignored
    @DeleteMapping("/api/users/{id}")
    void delete(@PathVariable String id) { users.deleteById(id); }
}

Without @EnableMethodSecurity, @PreAuthorize, @PostAuthorize and @Secured are plain annotations. The code reads as protected and isn't.

Vulnerable — one sibling forgotten

@PostMapping("/{projectId}/members")
public Invitation invite(@PathVariable String projectId, @RequestBody InviteRequest body) {
    return projects.invite(projectId, CurrentUser.id(), body.username(), body.role());  // checks admin
}

@DeleteMapping("/{projectId}/members/{userId}")
public void remove(@PathVariable String projectId, @PathVariable String userId) {
    Project project = projects.getForMember(projectId, CurrentUser.id());   // member only
    store.removeMember(project.getId(), userId);                            // gap
}

Vulnerable — URL rule doesn't match what the controller serves

http.authorizeHttpRequests(auth -> auth
        .requestMatchers(HttpMethod.GET, "/admin/**").hasRole("ADMIN")   // only GET
        .anyRequest().authenticated());

POST /admin/users/5/role matches no admin rule and falls through to authenticated().

Mitigated — URL rules for whole areas

http.authorizeHttpRequests(auth -> auth
        .requestMatchers("/admin/**", "/api/admin/**").hasRole("ADMIN")   // every method
        .requestMatchers("/login", "/register").permitAll()
        .anyRequest().authenticated());

A new route added under /admin is covered by default. Keep the most specific matchers first, since the first match wins.

Docs: Authorize HTTP requests

Mitigated — method security

@Configuration
@EnableMethodSecurity                         // turns the annotations on
class MethodSecurityConfig { }

@PreAuthorize("hasRole('ADMIN')")             // on the class: every method is covered
@RestController
@RequestMapping("/api/admin/users")
class UserAdminController {
    @DeleteMapping("/{id}")
    void delete(@PathVariable String id) { users.deleteById(id); }
}

Docs: @EnableMethodSecurity

Mitigated — per-resource role in one place

@Component("projectAccess")
class ProjectAccess {
    boolean isAdmin(String projectId, Authentication auth) {
        Project p = projects.findById(projectId);
        String role = p == null ? null : p.roleOf(auth.getName());
        return "owner".equals(role) || "admin".equals(role);
    }
}

@PreAuthorize("@projectAccess.isAdmin(#projectId, authentication)")
@DeleteMapping("/{projectId}/members/{userId}")
public void remove(@PathVariable String projectId, @PathVariable String userId) { … }

Or call one requireAdmin(projectId, userId) helper at the top of every service method that manages members, so the rule can't drift between invite, role change and remove.

Docs: Using beans in expressions

Bypasses to check

  • @PreAuthorize / @Secured / @RolesAllowed with no @EnableMethodSecurity (or @EnableGlobalMethodSecurity in old code without prePostEnabled = true, securedEnabled or jsr250Enabled).
  • Annotations on a method called from the same class (this.delete(id)): Spring's proxy is skipped, so the check doesn't run. Private methods are never proxied either.
  • hasRole('ADMIN') vs hasAuthority('ADMIN'): hasRole adds the ROLE_ prefix. A mismatch denies everyone, and the "fix" is often to loosen the rule.
  • requestMatchers limited to one HttpMethod, or a pattern that doesn't cover the real path (/admin/* vs /admin/**, a different servlet path, a path variable segment).
  • The same action reachable by two routes (the JSON API and the server-rendered form controller), with the check in only one controller instead of the shared service.
  • Check then change: the role is validated from the request (role.equals("owner") rejected), then stored after toLowerCase() or trim(), so " Owner" becomes owner. Validate against an allowlist after normalising, and store the normalised value.
  • Spring Data REST exposing repositories (/profile, /users) with no rules at all, or Actuator endpoints (/actuator/env, /actuator/heapdump).

What to grep for

  • @EnableMethodSecurity, @EnableGlobalMethodSecurity, @PreAuthorize, @PostAuthorize, @Secured, @RolesAllowed
  • requestMatchers(, HttpMethod., hasRole(, hasAuthority(, anyRequest()
  • isAdmin, requireAdmin, roleOf, getRole() in services
  • spring-boot-starter-data-rest, @RepositoryRestResource, management.endpoints

Mitigation options

Option When it fits Docs
A role decorator next to login_required A few fixed roles Flask view decorators
A blueprint before_request that requires a role A whole area (/admin) shares one rule Blueprint.before_request
Per-resource roles checked in the loader (need='admin') Roles that differ per project or repository flask.abort

Vulnerable — the UI hides the button, the route doesn't check

@app.post('/projects/<pid>/members/<uid>/remove')
@login_required
def remove_member(pid, uid):          # any logged-in member can call it
    db.projects.update_one({'_id': ObjectId(pid)}, {'$pull': {'members': {'user_id': uid}}})
    return redirect(url_for('members', pid=pid))

Vulnerable — the role check runs on GET only

@app.route('/settings', methods=['GET', 'POST'])
def settings():
    if request.method == 'GET':
        require_admin()
        return render_template('settings.html')
    save_settings(request.form)        # POST skips the check

Vulnerable — the web route checks, the API sibling doesn't

@bp.post('/<owner>/<name>/branches/delete')
def delete_branch_web(owner, name):
    repo = load_repo(owner, name, need='write'); ...

@api.delete('/repos/<rid>/branches/<branch>')
@require_token
def delete_branch_api(rid, branch):
    repo = repos.find_by_id(rid); git.delete_branch(rid, branch)   # no write check

Mitigated — check the role on the server, per route

def require_role(*roles):
    def deco(view):
        @wraps(view)
        def wrapped(*a, **kw):
            if not g.user or g.user['role'] not in roles:
                abort(403)
            return view(*a, **kw)
        return wrapped
    return deco

@admin_bp.before_request
def _admin_only():                 # runs before every view in the blueprint, including ones added later
    if not g.user:
        return redirect(url_for('auth.login', next=request.path))
    if g.user['role'] != 'admin':
        abort(403)

Docs: Flask view decorators · Blueprint.before_request

Mitigated — roles you can grant are capped

COLLABORATOR_ROLES = ('read', 'write')          # 'admin' can't be granted through this route
if request.form.get('role') not in COLLABORATOR_ROLES:
    abort(400)

Bypasses to check

  • Decorator order. In Flask the decorator closest to the function runs first, so @login_required placed above @app.route is never applied.
  • methods=['GET', 'POST'] views whose check covers only one branch.
  • API and web blueprints that duplicate an action. Check that both sides check the role.
  • Role values taken from the form when granting roles, such as role=admin or role=owner.

What to grep for

  • @login_required, before_request, abort(403), role, is_admin, need=
  • methods=[, request.method ==, @api., @bp.

Resources