Add JWT login and protected route handlers to a Next.js app with algorithm-pinned verification, expiry checks, HttpOnly cookies and correct 401 responses.
Implement JWT-based authentication for Next.js API routes: a login endpoint that issues a token and a protected endpoint that verifies it. Verify authentication inside each protected handler, not only in middleware/proxy. If the project already uses an authentication library (for example Auth.js) or an identity provider, integrate with it instead of writing token code. ## Inputs Next.js version and router (App Router `route.ts` or Pages Router `pages/api`): [NEXT_VERSION_AND_ROUTER] User store and password hashing already in place: [USER_STORE] Token transport (HttpOnly cookie for browser clients, Authorization header for API clients): [TRANSPORT] Signing method and key source (HS256 with a secret from an environment variable, or RS256/ES256 with a key pair): [SIGNING] Token lifetime, issuer and audience: [CLAIMS_POLICY] Protected routes: [PROTECTED_ROUTES] ## Instructions 1. `POST /api/auth/login`: validate `username` and `password`, verify the password hash with constant-time comparison, and return the same 401 message for an unknown user or a wrong password. 2. Issue a JWT with `sub`, `iat`, `exp`, `iss` and `aud`. Keep the payload free of secrets and personal data the client does not need. 3. Deliver the token by [TRANSPORT]. For cookies set HttpOnly, Secure, SameSite and Path, and add CSRF protection for state-changing requests. 4. Write one `verifyToken` helper that pins the accepted algorithm(s), checks signature, `exp`, `iss` and `aud`, and rejects `alg: none`. Use a maintained library (for example `jose`, which also runs on the Edge runtime). 5. Protected handler (`/api/protected`): call the helper and return 401 with `WWW-Authenticate` for missing, malformed, expired or invalid tokens; return 403 when the token is valid but the user lacks permission. 6. Logout clears the cookie. Explain how revocation works (short expiry plus refresh, or a server-side deny list). 7. Load secrets from environment variables and fail at startup if they are missing. ## Return 1. Login route code. 2. Protected route code. 3. `verifyToken` helper and how token verification works. 4. Example requests and responses: successful login, invalid credentials (401), valid token, expired token (401), tampered token (401), insufficient permission (403). 5. Tests for each case above. ## Acceptance checks - Verification pins algorithms and checks `exp`, `iss` and `aud`. - Every protected handler verifies the token itself. - No hard-coded secret or sample token is used in code. - Error bodies do not reveal which credential was wrong.
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Next.js: 15, App Router, Node.js runtime User store: Prisma User model with passwordHash (argon2) Transport: HttpOnly cookie named session for the same-origin web app Signing: HS256 with JWT_SECRET from the environment Claims: 15-minute expiry, iss "https://app.example.com", aud "app-web" Protected routes: /api/protected and /api/reports/*
app/api/auth/login/route.ts that verifies the argon2 hash and sets an HttpOnly, Secure, SameSite=Lax session cookie containing a jose-signed HS256 token with a 15-minute exp; lib/auth/verifyToken.ts using jwtVerify with algorithms: ['HS256'], issuer and audience; app/api/protected/route.ts that calls it and returns 401 for missing, expired or tampered tokens; a CSRF note for POST routes; and examples covering all six cases. The example tokens are generated in tests rather than copied from a public sample token. Illustrative expectation; a Node crypto fixture executed locally confirmed that a tampered signature and an expired exp are rejected by an algorithm-pinned HS256 check (see report).
Ask questions or share concrete improvements.
No comments yet.
Sign in to join the discussion.
Guides for adapting and checking prompts: