> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Authorization Implementation

> Guide for auditing and implementing authorization in Express apps, covering BOLA, RBAC, JWT validation, middleware ordering, remediation steps and deliverables.

Authentication is assumed to be present. This lesson focuses on the next critical step: authorization — verifying which identities can access which resources and operations across an Express application.

The supporting repository and the automated audit artifacts referenced throughout this guide are available on GitHub:
[https://github.com/JeremyMorgan/Claude-Code-Reviewing-Prompts](https://github.com/JeremyMorgan/Claude-Code-Reviewing-Prompts)

```text theme={null}
4. Reduce token expiration to 15 minutes
5. Add refresh token mechanism

The application should not handle real user data in its current state due to critical security vulnerabilities.

◦jeremy@MACSTUDIO Express-login-demo % claude

* Welcome to Claude Code!

/help for help, /status for your current setup

cwd: /Users/jeremy/Repos/Claude Code Course/Express-login-demo

What's new:
• Status line input now includes session cost info

> [Pasted text #1 +114 lines]
```

Summary

* Purpose: Provide a practical checklist and remediation guidance for authorizing routes, preventing BOLA/IDOR, enforcing RBAC, verifying JWT usage, and closing privilege escalation vectors.
* Audience: Backend engineers, security reviewers, and dev teams auditing Express apps for authorization issues.
* Output: A reproducible checklist, example code snippets for fixes, proof-of-concept notes, and prioritized remediation steps.

Authorization checklist (core items)

| Core Item | What to verify | Quick test / expectation |
| - | -: | - |
| 1. Broken Object Level Authorization (BOLA / IDOR) | Verify ownership/tenant checks on all object-level routes (`GET/PUT/DELETE /:id`) | Identifiers in URL/body/query cannot be used to access others' data; per-item checks exist |
| 2. Broken Function Level Authorization | Ensure role/permission checks on privileged routes, enforced server-side | Routes that perform admin actions require server-side role checks |
| 3. Missing checks on sensitive endpoints | Confirm middleware ordering (authN → authZ → handler) and no exposed admin/debug endpoints | No unprotected endpoints that allow exports, resets, or admin actions |
| 4. Role-based access control (RBAC) | Map roles → permissions; enforce deny-by-default | Roles cannot be set/changed by client input |
| 5. Privilege escalation | Ensure update endpoints disallow fields like `role`, `tenantId`, `isAdmin` | Multi-step workflows do not allow indirect escalation |
| 6. JWT validation | Verify `jwt.verify` with strict `algorithms`, `iss`, `aud`, `exp` enforcement | No uses of `jwt.decode` for trust decisions; implement revocation (`jti`/`tokenVersion`) |
| 7. API token scopes | Enforce least privilege scopes and differentiate user vs service tokens | `aud` and scope checks prevent service tokens from acting as users |

Additional items to check

| Item | Concern |
| - | - |
| 8. Multi-tenant isolation | Tenant constraints must be injected server-side and enforced in queries |
| 9. Bulk endpoint protections | Batch operations must validate ownership per-item, not only once |
| 10. Field-level authorization | Sensitive fields excluded from responses for non-privileged users |
| 11. Error handling & resource enumeration | Uniform errors; return 403 for authenticated-but-unauthorized or 404 if intentionally hiding existence |
| 12. Middleware ordering | authN → authZ → handler; nested routers must inherit protections |
| 13. CORS & CSRF | No wildcard origins with credentials; if cookies used, set SameSite and CSRF tokens |
| 14. Open redirect protections | Whitelist `redirect`/`next` parameters after login |
| 15. Fallback/debug routes | Ensure `/seed`, `/reset`, `/debug` are admin-only or removed in production |

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/Xs8Ruv7b0QCZf7iM/images/Claude-Code-for-Beginners/Security-Auditing-with-Claude-Code/Authorization-Implementation/vscode-security-audit-rbac-jwt-checklist.jpg?fit=max&auto=format&n=Xs8Ruv7b0QCZf7iM&q=85&s=f3e6acaa561826d91f84c10f3b380f79" alt="A dark-themed code editor (Visual Studio Code) with a file explorer on the left. The main pane displays a security-audit checklist covering role-based access control, JWT validation, privilege escalation checks, and API token scopes." width="1920" height="1080" data-path="images/Claude-Code-for-Beginners/Security-Auditing-with-Claude-Code/Authorization-Implementation/vscode-security-audit-rbac-jwt-checklist.jpg" />
</Frame>

Key points to emphasize

* Multi-tenant isolation must be enforced server-side. Client-side tenant selectors are not a security boundary.
* Bulk operations must check ownership at the per-item level; do not assume the caller is authorized for every item in a batch.
* Field-level authorization (or server-side projection) is required to avoid leaking sensitive fields.
* Use a consistent error policy to avoid resource enumeration: choose 403 for authenticated-but-unauthorized; use 404 only when intentionally hiding existence.
* Middleware ordering must always be: authentication (authN) → authorization (authZ) → handler. Misordered middleware is a common bypass.

For each endpoint you should answer

* Who can access it? (roles, scopes, tenant)
* What data can they see or modify (including hidden fields)?
* Are ownership/tenancy checks enforced (query-level filter + post-fetch verification)?
* Are authN/authZ middleware enforced consistently and in the correct order?

Deliverables for each finding

For any issue discovered, produce:

* Title, Severity (Critical/High/Medium/Low), CWE (if applicable)
* Evidence (file, function, line ranges)
* Short explanation: Why it matters
* Exploitability notes and safe PoC steps (no real secrets)
* Remediation: precise code-level fix or config change (include snippets)
* Defense-in-depth guidance
* Summary risk score (0–10) and top prioritized fixes
* Checklist diff: which items are Pass / Fail / N/A

Callout — critical reminder

<Callout icon="warning" color="#FF6B6B">
  Authorization failures are often catastrophic. If you find missing authorization middleware, weak JWT validation, or endpoints that accept role changes from clients, treat these as critical and fix them before any production deployment.
</Callout>

Example findings and minimal remediation snippets

1. Weak / incomplete JWT issuance

Problem: Tokens are signed without explicit algorithm, issuer, audience, or short expiration. Default secrets in env allow token forgery.

Remediation (example token issuance):

```javascript theme={null}
// javascript
const jwt = require('jsonwebtoken');

const token = jwt.sign(
  {
    sub: String(user.id),
    email: user.email,
    // optionally include a tokenVersion or jti for revocation checks
  },
  process.env.JWT_SECRET, // use a high-entropy secret (e.g., 256-bit) or prefer asymmetric keys (RS256) for production
  {
    algorithm: 'HS256',
    expiresIn: '15m',
    issuer: 'your-app.example.com',
    audience: 'your-app-users',
  }
);
```

2. Enforce ownership on object-level routes

Problem: Routes accepting `/:id` may be vulnerable to BOLA/IDOR if they do not verify resource ownership.

Remediation (authorization middleware):

```javascript theme={null}
// javascript
const authorizeOwnership = (pool) => async (req, res, next) => {
  try {
    const resourceId = req.params.id;
    const userId = req.user && req.user.sub; // set by authentication middleware

    const result = await pool.query(
      'SELECT user_id FROM resources WHERE id = $1',
      [resourceId]
    );

    if (result.rows.length === 0) {
      return res.status(404).json({ error: 'Resource not found' });
    }

    if (String(result.rows[0].user_id) !== String(userId)) {
      return res.status(403).json({ error: 'Access denied' });
    }

    next();
  } catch (err) {
    next(err);
  }
};

module.exports = { authorizeOwnership };
```

3. Authentication middleware must run before route handlers

Example pattern:

```javascript theme={null}
// javascript
const { authenticateToken } = require('./middleware/authenticateToken');
const { authorizeOwnership } = require('./middleware/authorizeOwnership');

app.use('/api', authenticateToken); // authN
app.use('/api/admin', authorizeAdmin); // authZ for admin routes

// For a resource route that needs ownership check
app.get('/api/resources/:id', authorizeOwnership(pool), getResourceHandler);
```

Proof of concept (why it is exploitable)

If no auth middleware is attached, any future POST/PUT/DELETE endpoints will be accessible to anonymous users. To demonstrate locally:

```bash theme={null}
# public endpoint
curl -i http://localhost:3000/

# login to get token (example)
curl -i -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@example.com","password":"password"}'
```

If the server does not require the token for privileged routes, any client can perform state-changing operations without authorization.

Assessment sample (from automated audit)

* Authorization Security Assessment Complete
* Risk Score: 9.5/10 (Critical)

Critical findings (examples)

* No authentication middleware — endpoints are unprotected.
* Weak JWT implementation — missing algorithm, issuer, audience validation.
* Default secrets present — allows token forgery.
* No authorization framework — vulnerable to BOLA/IDOR.

Immediate actions (short-term)

* Replace default JWT secret with a 256-bit cryptographically secure value.
* Implement authentication middleware before adding any protected endpoints.
* Configure JWT verification to require `algorithms`, `issuer`, and `audience`, and ensure expiration (`exp`) is enforced.
* Disallow client-side role or tenant updates; accept those only via server-side admin flows.

Defense-in-depth recommendations

* Application: comprehensive authN/authZ middleware, RBAC mapping, and field-level filtering.
* Infrastructure: rate limiting, WAF, secure defaults for secrets and environment variables.
* Database: enforce row-level security when available (e.g., PostgreSQL RLS) and use least-privilege DB users.
* Monitoring: log auth events and alert on suspicious access patterns.
* Testing: automated tests for BOLA/IDOR, RBAC, and token validation in CI.

Assessment artifacts and reporting

Produce a structured report per issue containing:

* Title, Severity, CWE, Evidence (file/function/line ranges), Why it matters.
* Safe reproduction steps and remediation code snippets.
* A prioritized list of fixes and a checklist diff (Pass/Fail/N/A).

Wrap-up

Automated code-generation tools can accelerate development, but they often produce code lacking hardening assumptions (default secrets, missing authZ, etc.). Use automated audits to find these gaps, apply minimal, specific fixes above, and re-run tests and audits.

The prompts and audit artifacts referenced in this lesson/article are available at:
[https://github.com/JeremyMorgan/Claude-Code-Reviewing-Prompts](https://github.com/JeremyMorgan/Claude-Code-Reviewing-Prompts)

<Callout icon="lightbulb" color="#1CB2FE">
  Use short-lived access tokens (e.g., 15 minutes) and implement a refresh token mechanism with strict rotation and revocation. Always validate `algorithms`, `iss`, and `aud` in `jwt.verify`, and ensure token expiration (`exp`) checks are enforced.
</Callout>

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/claude-code-for-beginners/module/eaf75a67-f28f-4217-a3f9-92d411403129/lesson/7776d385-de2b-4b34-ac18-a5ca70dcb773" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.