Authentication
JWT tokens, password hashing, protected routes, and roles
Overview
Authentication is built on node:crypto — there is no bcrypt or jsonwebtoken dependency. Token and password helpers come from@basicbenframework/core/auth, and roles come from@basicbenframework/core/auth/permissions.
Stateless authentication, signed HS256
Salted password storage
Decide who may do what
The Signing Secret
The framework does not hold a secret of its own and reads nothing frombasicben.config.js for auth. Every call that signs or verifies a token takes the secret as an argument, so you decide where it comes from. The convention across the generated app is process.env.APP_KEY, set in .env.
APP_KEY=a-long-random-string
Passing the secret explicitly means signing and verification cannot silently drift apart, and a route that mints tokens for a different audience can use a different key. Changing APP_KEY invalidates every token already issued, which is the blunt way to sign everybody out.
Password Hashing
Passwords are hashed with scrypt. Each hash gets its own random salt, and verification uses a timing-safe comparison. Both hashPassword andverifyPassword are async, so both need await.
import { hashPassword, verifyPassword } from '@basicbenframework/core/auth'
// Registration: hash before storing
const hash = await hashPassword('correct-horse-battery-staple')
// Login: compare the submitted password against the stored hash
const isValid = await verifyPassword('correct-horse-battery-staple', hash)
// true
await verifyPassword('wrong-password', hash)
// falseThe stored value is a single string holding the salt, the derived key, and the parameters used to produce it, in the formatbase64(salt):base64(hash):N:r:p:keylen. Because the parameters travel with the hash, raising the cost later does not lock existing users out — old hashes still verify against their own settings. A TEXT column is all you need.
import { hashPassword, verifyPassword, needsRehash } from '@basicbenframework/core/auth'
// After a successful login, while you still have the plain password
if (await verifyPassword(password, user.password) && needsRehash(user.password)) {
await User.update(user.id, { password: await hashPassword(password) })
}needsRehash compares the parameters stored in the hash against the current defaults, or against options you pass as a second argument. It is the only one of the three that is synchronous.
JWT Tokens
signJwt and verifyJwt are synchronous. There is nothing to await, and no try/catch to write: verifyJwt returns the decoded payload, or null when the token is missing, malformed, signed with another secret, or expired.
import { signJwt, verifyJwt } from '@basicbenframework/core/auth'
// After checking a password
const token = signJwt(
{ userId: user.id, role: user.role },
process.env.APP_KEY,
{ expiresIn: '7d' }
)
// Later, on an incoming request
const payload = verifyJwt(token, process.env.APP_KEY)
if (!payload) {
// No token, wrong signature, or expired — treat as signed out
}
payload.userId // 1
payload.role // 'admin'
payload.iat // issued at, seconds since the epoch
payload.exp // expires at, present only when expiresIn was givenexpiresIn takes a number of seconds, or a string with a unit:'60s', '5m', '2h', '7d'. Leave it out and the token never expires, which is rarely what you want. Tokens are signed HS256, and signJwt throws when the secret is missing rather than signing with an empty key.
import { decodeJwt } from '@basicbenframework/core/auth'
// Returns the payload of any well-formed token, signature unchecked
const payload = decodeJwt(token)decodeJwt is for logging and debugging — reading the user id out of an expired token, for instance. It proves nothing about the token, so never make an access decision from its result.
The payload is signed, not encrypted. Anyone holding the token can read it, so put identifiers in it and keep secrets out.
Registration
A registration endpoint validates the input, stores a hash rather than the password, and returns a token so the new user is signed in immediately.
import { query } from '@basicbenframework/core/db'
import { validate, rules } from '@basicbenframework/core/validation'
import { hashPassword, signJwt } from '@basicbenframework/core/auth'
import { ROLES, DEFAULT_ROLE } from '@basicbenframework/core/auth/permissions'
export const AuthController = {
async register(req, res) {
const result = await validate(req.body, {
name: [rules.required, rules.min(2)],
email: [rules.required, rules.email, rules.unique('users')],
password: [rules.required, rules.min(8)]
})
if (result.fails()) {
return res.json({ errors: result.errors }, 422)
}
const { name, email, password } = req.body
// The first account to register is the operator setting the site up, so it
// becomes the admin. Everyone after gets the least privileged role.
const isFirstUser = (await (await query('users')).count()) === 0
const role = isFirstUser ? ROLES.ADMIN : DEFAULT_ROLE
const { lastInsertRowid } = await (await query('users'))
.only('name', 'email', 'password', 'role')
.insert({
name,
email,
password: await hashPassword(password),
role
})
const token = signJwt({ userId: lastInsertRowid, role }, process.env.APP_KEY, {
expiresIn: '7d'
})
return res.json({ user: { id: lastInsertRowid, name, email, role }, token }, 201)
}
}The role is decided on the server from the number of existing users. Never read it out of req.body — that would let anyone register as an administrator.
.only(...) names the columns the insert may write. From 0.9 aninsert() or update() without it (or .unguarded()) throws an error with code: 'MASS_ASSIGNMENT', so a stray rolekey in a request body can never reach the table.
Login
Login looks the user up, compares the password against the stored hash, and issues a token carrying the user id and role.
import { query } from '@basicbenframework/core/db'
import { verifyPassword, signJwt } from '@basicbenframework/core/auth'
import { DEFAULT_ROLE } from '@basicbenframework/core/auth/permissions'
export const AuthController = {
async login(req, res) {
const { email, password } = req.body
if (!email || !password) {
return res.json({ error: 'Email and password required' }, 400)
}
const user = await (await query('users')).where('email', email).first()
// One message for both failures, so the response does not reveal which
// addresses have accounts.
if (!user || !(await verifyPassword(password, user.password))) {
return res.json({ error: 'Invalid credentials' }, 401)
}
const role = user.role ?? DEFAULT_ROLE
const token = signJwt({ userId: user.id, role }, process.env.APP_KEY, {
expiresIn: '7d'
})
return res.json({
user: { id: user.id, name: user.name, email: user.email, role },
token
})
}
}The early return for a missing email matters on 0.9: a where() givenundefined throws an error with code: 'UNDEFINED_VALUE', rather than guessing what a missing input meant. Only a literal null meansIS NULL.
res.json(data, status) takes the status code as a second argument.res.status(status).json(data) works too — use whichever reads better.
Auth Middleware
The middleware pulls the token off the Authorization header, verifies it, and puts the result on the request. Everything downstream reads req.userinstead of touching the token again.
import { verifyJwt } from '@basicbenframework/core/auth'
import { DEFAULT_ROLE } from '@basicbenframework/core/auth/permissions'
// Named export only, deliberately. See the note below.
export const auth = async (req, res, next) => {
const token = req.headers.authorization?.replace('Bearer ', '')
if (!token) {
return res.json({ error: 'Unauthorized' }, 401)
}
const payload = verifyJwt(token, process.env.APP_KEY)
if (!payload) {
return res.json({ error: 'Invalid token' }, 401)
}
req.userId = payload.userId
req.user = { id: payload.userId, role: payload.role ?? DEFAULT_ROLE }
next()
}Export it as auth, not as the default. Any default export from a file in src/middleware/ is loaded automatically and applied to every request in the application. Default-exporting this function would therefore demand a valid token for the login endpoint, the registration endpoint, and every public page — an app that returns 401 to everyone, including the people trying to sign in. Reserve default exports for middleware that genuinely belongs on every request, such as request logging.
Verifying a token costs nothing but an HMAC, so this middleware does not touch the database. When a handler needs the full record, load it there fromreq.userId. Loading the user on every request also picks up a role change immediately, which the token alone will not do.
Protecting Routes
A route file default-exports a function that receives the router. Middleware goes between the path and the handler, and runs before it.
import { PostController } from '../../controllers/PostController.js'
import { auth } from '../../middleware/auth.js'
export default (router) => {
// Public
router.get('/api/feed', PostController.feed)
router.get('/api/feed/:id', PostController.feedShow)
// Requires a valid token
router.get('/api/posts', auth, PostController.index)
router.post('/api/posts', auth, PostController.store)
router.put('/api/posts/:id', auth, PostController.update)
router.delete('/api/posts/:id', auth, PostController.destroy)
}It has to be a function. The loader imports each file undersrc/routes/ and calls the default export only when it is a function, so a file that default-exports an array of route objects registers nothing and reports no error — the endpoints simply return 404. If a route you just added cannot be reached, check the shape of the export first.
Roles and Capabilities
Authentication says who the user is; capabilities say what they may do. Roles ship with a fixed set of capabilities named resource.action, and handlers ask about the capability rather than the role — so the check keeps working if the roles are rearranged later.
adminEverything, including settings, users and API tokens
editorCreate, edit, publish and delete any post or page
authorCreate and publish posts, edit and delete their own
contributorWrite and edit their own drafts, but not publish or upload media
subscriberComment only. The default for new accounts
import { can } from '@basicbenframework/core/auth/permissions'
can(req.user, 'settings.manage') // true only for admin
can(req.user, 'post.create') // true from contributor upward
// Ownership-scoped capabilities need the record being acted on
can(req.user, 'post.edit', post)A role may hold the .own variant of an action instead of the plain one. An author holds post.edit.own, so can(user, 'post.edit', post)is true for their own post and false for someone else’s. Ownership is read from the record’s user_id, author_id or userId, whichever is present. Without a record to compare against, an ownership-scoped capability cannot be granted, so the check returns false — pass the resource whenever there is one.
import { requireCapability, requireRole, ROLES } from '@basicbenframework/core/auth/permissions'
import { PostController } from '../../controllers/PostController.js'
import { UserController } from '../../controllers/UserController.js'
import { auth } from '../../middleware/auth.js'
import { Post } from '../../models/Post.js'
export default (router) => {
// 403 unless the user may edit this particular post
router.put(
'/api/posts/:id',
auth,
requireCapability('post.edit', { loadResource: (req) => Post.find(req.params.id) }),
PostController.update
)
// Role check, where a capability does not fit
router.get('/api/admin/users', auth, requireRole(ROLES.ADMIN), UserController.index)
}requireCapability reads req.user, so it always goes afterauth. It answers 401 when there is no user and 403 when the capability is missing. Given a loadResource function it loads the record first, answers 404 if there is none, and otherwise leaves it on req.resource for the handler — so the row is fetched once, not twice.
import { capabilitiesFor, ROLES, DEFAULT_ROLE } from '@basicbenframework/core/auth/permissions'
capabilitiesFor(ROLES.ADMIN)
// ['*']
capabilitiesFor(ROLES.CONTRIBUTOR)
// ['post.create', 'post.edit.own', 'post.delete.own', 'comment.create']
DEFAULT_ROLE
// 'subscriber'The first account to register becomes the admin, on the assumption that it belongs to whoever is setting the site up. Everyone after that gets DEFAULT_ROLE.
The role travels in the token, which is what makes these checks free. The cost is that promoting or demoting a user changes nothing until their token is reissued. Where that delay matters — revoking an administrator, say — reload the user in the handler and pass the fresh record to can() rather than trustingreq.user.
On the Client
useAuth exposes the signed-in user and the two functions that change that state. The token lives in localStorage under token; on startup the router sends it to /api/user to find out who it belongs to, and loading is true until that answer arrives. With no token stored, there is nothing to check and the first render is the page itself.
/api/user is the default of the authEndpoint option tocreateClientApp(). Point it somewhere else, or set it to falseto skip the check, in which case nobody is signed in until setUser says so.
createClientApp({
routes,
authEndpoint: '/api/me' // or false
})import { useAuth } from '@basicbenframework/core/client'
export function Profile() {
const { user, logout, loading } = useAuth()
if (loading) return null
if (!user) return null
return (
<div>
<p>{user.name} ({user.role})</p>
<button onClick={logout}>Sign out</button>
</div>
)
}After a successful login, store the token and hand the user to setUser. The api helper reads the token back out of localStorage and sends it as an Authorization: Bearer header on later requests.
import { useAuth, useNavigate } from '@basicbenframework/core/client'
import { api } from '../../helpers/api'
export function Login() {
const { setUser } = useAuth()
const navigate = useNavigate()
const submit = async (e) => {
e.preventDefault()
const data = await api('/api/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password })
})
localStorage.setItem('token', data.token)
setUser(data.user)
navigate('/')
}
// ...
}logout does the reverse: it POSTs the token tologoutEndpoint (default /api/auth/logout, falseto skip it) without waiting for an answer, clears the token, forgets the user, and goes to homePath (default /).
export const App = createClientApp({
routes: {
'/': Home,
// Signed out only — a signed-in visitor is sent to /
'/login': { component: Auth, layout: AuthLayout, guest: true },
'/register': { component: Auth, layout: AuthLayout, guest: true },
// Signed in only — a signed-out visitor is sent to /login
'/posts': { component: Posts, auth: true },
'/profile': { component: Profile, auth: true }
}
})The guards redirect after render: a guarded route renders nothing, and an effect then navigates to loginPath (default /login) orhomePath (default /), replacing the history entry. Before 0.9 they called navigate() during render.
These guards decide what to render, nothing more. They keep a signed-out visitor from landing on a page that has no data to show, but anyone can call your API directly, so every protected route still needs the auth middleware on the server.