---
title: Authentication & authorization
summary: Who are you (authN) and what are you allowed to do (authZ). Get this wrong and nothing else matters.
section: backend
phase: build
order: 2
last_reviewed: 2026-11-20
---

# Authentication & authorization

**Authentication** proves who the user is. **Authorization** decides what they can do. Agents get authentication mostly right and often skip authorization entirely.

## You'll be able to
- Choose between rolling your own auth, a library, and a hosted provider
- Understand sessions vs JWTs, OAuth, and passkeys well enough to specify them
- Demand and verify authorization checks

## The mental model
Login produces a **credential** (a session cookie or a token). Every later request carries it. The server **verifies** the credential (authN), then checks the **permission** for the specific action and resource (authZ).

## Key concepts
- **Password hashing:** Never store passwords. Store a slow hash made with **Argon2id** or **bcrypt**.
- **Session-based auth:** The server stores the session and the browser holds an opaque ID in an `HttpOnly`, `Secure`, `SameSite` cookie. Sessions are easy to revoke. **This is the default for web apps.**
- **JWT:** A signed token that carries claims. The server doesn't need to store it, but revoking one is hard. Best for service-to-service or short-lived API access. Don't store JWTs in `localStorage`.
- **OAuth 2.0 / OpenID Connect:** "Sign in with Google/GitHub." OIDC adds identity on top of OAuth.
- **Magic links / OTP:** Passwordless login by email or SMS code.
- **Passkeys (WebAuthn):** Phishing-resistant, device-based credentials. This is where login is heading.
- **MFA:** A second factor (an authenticator app, a passkey).
- **RBAC / ABAC:** Role-based ("admins can delete") vs attribute-based ("owners can edit their own posts") access control.
- **Row-level security (RLS):** Authorization enforced inside the database itself (Postgres/Supabase).
- **CSRF:** Tricking a logged-in browser into sending a request. Mitigate with `SameSite` cookies and CSRF tokens.

> **Note:** OWASP's Password Storage cheat sheet names **Argon2id as the first choice**, with scrypt next, and bcrypt only for legacy systems where neither is available (with its input-length limit enforced). Fast hashes such as SHA-256 are not suitable for passwords.

> **Note:** OWASP's Authorization cheat sheet prefers attribute-based and relationship-based checks over plain roles for application development. Roles alone are weak for object-level checks ("can this user see *this* order?") and for multi-tenant apps. Plan for ownership checks from the start.

## Decisions you make (not the agent)
| Decision | Sensible default | Choose otherwise when… |
|---|---|---|
| Build vs buy | Library (Better Auth, Auth.js, Lucia-style patterns) or hosted (Clerk, Supabase Auth, Auth0, WorkOS) | Never hand-roll crypto |
| Credential | Session cookie | Mobile/third-party API → short-lived tokens + refresh |
| Login methods | Email + OAuth (Google/GitHub); add passkeys | Enterprise → SSO/SAML (WorkOS etc.) |
| Authorization | Central permission helper called in every handler | Multi-tenant + Postgres → also RLS |

## What good output looks like

- Authentication comes from a vetted library or provider, with no custom crypto
- Sessions use cookies, and session IDs never appear in URLs
- Login and password-reset errors are the same whether or not the account exists
- Every handler checks permission for the specific object on the server, and the default answer is deny
- There are tests where one user tries to read or change another user's data

## Red flags
- Plain-text or fast-hashed (MD5/SHA-1) passwords
- JWTs in `localStorage`
- Permission checks only in the UI (a hidden button is not security)
- "Admin" decided by a client-sent flag
- Login errors that reveal whether an account exists
- No rate limiting on login or password reset
- **Common agent mistakes:** a handler that checks "is the user logged in?" but not "does this record belong to them?" (anyone can change the ID in the URL); access that is allowed unless a rule says no; forced periodic password changes or rigid composition rules, which OWASP advises against; session IDs passed in URLs

## Worked example

**Task:** Add an order details endpoint, `GET /api/orders/[id]`.

You prompt: *"Add an endpoint that returns an order by ID for the logged-in user."* The agent writes a handler that confirms the user is logged in and returns the order with that ID.

**What a good result contains:** the handler loads the order, checks that it belongs to the current user (or that the user's role allows access), and denies the request otherwise. Tests prove that another user gets refused.

**The wrong turn:** being logged in is not the same as being allowed. Any logged-in user can request `/api/orders/1042`, then `/api/orders/1043`, and read everyone's orders by changing the ID. This is an insecure direct object reference. OWASP's guidance is to check access to the specific object on every request, and notes that hiding or randomizing IDs is not enough on its own.

**How review catches it:** log in as user B and request an ID that belongs to user A. If you get a `200`, the check is missing. Then ask for a table of every route and its permission check, with deny as the default, and tests for the cross-user case.

## Sample prompts
```text
Add authentication to this Next.js app using <Better Auth>.
Methods: email+password and Google OAuth. Sessions in HttpOnly, Secure,
SameSite=Lax cookies. Passwords hashed with the library default (Argon2/bcrypt).
Add: email verification, password reset, rate limiting on login/reset,
and a requireUser() server helper. Protect /dashboard/* via middleware.
Don't build any custom crypto.
```
*Why it works:* It names the library, the cookie flags and the protections to include, and rules out custom crypto, so the agent has little left to improvise.

```text
Add role-based authorization: roles are owner, admin, member per organization.
Create a single can(user, action, resource) helper with a permissions table in
code. Call it in every server action and API route that reads or mutates
org data. Then list every route and show which permission check it uses. Flag
any route with no check.
```
*Why it works:* One central helper keeps the rule in one place, and the final audit step finds the routes the agent forgot.

### Test that users can't reach each other's data
```text
For every endpoint and server action that reads or changes user-owned data, write a test that logs in as user B and tries to access a record owned by user A, using its ID. The expected result is a refusal (403 or 404), never the data. Also test an unauthenticated request. Run the tests and show me the output. Don't weaken any existing check to make a test pass.
```
*Why it works:* It makes the most common authorization bug testable, and it requires proof that the check can actually fail.

### Audit authorization route by route
```text
Make a table of every API route and server action: the route, who is allowed to call it, which permission check it runs (and where), and what happens by default if no rule matches. Mark any route that checks only that the user is logged in and not that they may access the specific object. Don't change code yet.
```
*Why it works:* "Deny by default" and "check on every request" only mean something if you can see every route and its check in one place.

### Explain how login and sessions work here
```text
Explain how login works in this app: where the session ID is stored, the cookie flags it uses, how logout ends the session, what the login error says for a wrong password versus an unknown email, and what protects login and password reset from repeated attempts. Mark anything you are unsure of as unverified.
```
*Why it works:* It makes the agent state the facts you'll check against the code and the checklist. Treat unverified items as work to do.

## Check your understanding

```quiz
Q: A page hides the "Delete" button from non-admins, but the delete endpoint has no role check. Is that secure?
- [ ] Yes, ordinary users never see the button
- [x] No, anyone can call the endpoint directly. Access must be enforced on the server
- [ ] Yes, as long as the endpoint URL is hard to guess
> Why: Client-side checks improve the experience but can't decide access. A hidden button is not security.

---

Q: Logged-in user B changes /orders/1042 to /orders/1043 and sees user A's order. What is the flaw?
- [ ] Weak password hashing
- [x] Missing object-level authorization (an insecure direct object reference)
- [ ] A CSRF problem
> Why: The server confirmed who B is but never checked that B may see that order. Check access to the specific object on every request.

---

Q: What should the login page say when the password is wrong, and when the account does not exist?
- [ ] "No account with that email" and "Wrong password", so users know what to fix
- [x] The same generic message for both
- [ ] Nothing at all
> Why: Different messages let an attacker discover which accounts exist. OWASP recommends one generic response.

---

Q: Which is OWASP's first-choice algorithm for hashing passwords?
- [ ] SHA-256
- [ ] MD5
- [x] Argon2id
> Why: Passwords need a slow, adaptive hash with a unique salt. Fast hashes like SHA-256 are unsuitable, and bcrypt is for legacy systems where neither Argon2id nor scrypt is available.
```

## Checklist
- [ ] Passwords hashed with Argon2id/bcrypt (or no passwords at all)
- [ ] Cookies are `HttpOnly`, `Secure`, `SameSite`
- [ ] Every data access checks ownership or role on the server
- [ ] Login and reset are rate-limited
- [ ] Login and reset errors don't reveal whether an account exists
- [ ] The default is deny, and every route's check is listed in one place
- [ ] Tests prove user B can't read or change user A's data

## Go deeper
- [OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
- [OWASP Authorization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html)
- [passkeys.dev](https://passkeys.dev)
- [OWASP Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
- [OWASP Password Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html)
- [Security basics](/docs/security/security-basics.md): broken access control is the top web risk
- [Reviewing and verifying AI output](/docs/ai-agents/reviewing-ai-output.md): checking what the agent wrote
