API Tokens
Introduction
Personal access tokens let a script, a command line tool, or a third-party integration call your API on behalf of a user without a browser session or a password. @plinthjs/api-tokens issues those tokens, stores only a hash of each, and verifies them on every request. Each token can carry a list of abilities that limit what it may do, and an optional expiry.
pnpm add @plinthjs/api-tokensThe package has no HTTP middleware of its own. It gives you the token model, the issuing functions, a guard that checks a bearer token, and a store seam; you connect them to your routes with a few lines, shown below.
INFO
There are two different TokenGuard classes in the framework. The one in @plinthjs/auth authenticates a request through a user provider. The one in @plinthjs/api-tokens (this page) checks personal access tokens against a token store. Import from the package you mean.
How tokens work
A token is the string id|secret: a UUID that locates the stored record, a bar, and 80 hex characters of random secret. The server returns that plaintext exactly once, at creation. What it stores is the SHA-256 hash of the secret part, along with the name, abilities, owner, and expiry. A stolen database therefore does not reveal usable tokens.
Because the secret is long and random, a fast hash is appropriate here. Passwords are different (people choose them, and they are guessable), which is why they use the slow hasher described in Hashing.
Issuing tokens
Tokens are persisted in a TokenStore. ArrayTokenStore keeps them in memory, which suits tests. Create a token with createToken():
import { ArrayTokenStore, createToken } from '@plinthjs/api-tokens'
const store = new ArrayTokenStore()
const { plainTextToken, accessToken } = await createToken(store, {
name: 'Deploy script',
abilities: ['deployments:create'],
tokenableId: 1,
expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000,
})
plainTextToken // => '3f0c...|9ab7...' show this to the user once
accessToken.name // => 'Deploy script'
accessToken.abilities // => ['deployments:create']createToken() is async and resolves to two things. plainTextToken is the only copy of the usable token. accessToken is the stored record, which holds the hash but never the plaintext.
| Option | Meaning |
|---|---|
name | A human-readable label, such as the device or integration. |
abilities | What the token may do. Defaults to ['*'], meaning everything. |
expiresAt | Epoch milliseconds when it stops working. Omit for no expiry. |
tokenableId | The id of the owning user. |
tokenableType | A type name for the owner, useful when several models own tokens. |
Issuing tokens for a user
Most of the time a token belongs to a user. hasApiTokens(store, owner) binds the token API to one owner, so every token it issues carries the owner's id and type, and its listing is scoped to that owner:
import { hasApiTokens } from '@plinthjs/api-tokens'
const user = hasApiTokens(store, { id: 1, type: 'user' })
const { plainTextToken } = await user.createToken({
name: 'CLI',
abilities: ['posts:read', 'posts:write'],
})(await user.tokens()).length // => 1
await user.tokenCan('posts:read') // => true
await user.tokenCan('admin') // => falsetokens() lists only this owner's tokens, which is what you want for a "manage your tokens" page. tokenCan() reports whether any of the owner's tokens grants an ability.
TIP
Plinth has no mixins for this, so hasApiTokens() is a helper function rather than something you apply to your user class. Call it wherever you need it, for example in a controller: hasApiTokens(store, { id: user.id }).
Abilities
An ability is any string you choose. A token with ['*'] may do everything. Otherwise, a token can do exactly the abilities it lists. can() and cant() on a token do the check:
accessToken.can('deployments:create') // => true
accessToken.can('deployments:delete') // => false
accessToken.cant('deployments:delete') // => true
const all = await user.createToken({ name: 'Full access' }) // abilities default to ['*']
all.accessToken.can('anything') // => trueAbilities are matched exactly, with no hierarchy. If you want posts:*, grant the specific abilities you need.
Authenticating requests
TokenGuard takes a bearer token and returns the matching record, or null when the token is malformed, unknown, expired, or has the wrong secret. The secret comparison runs in constant time. On success, the token's lastUsedAt is updated and saved.
import { TokenGuard } from '@plinthjs/api-tokens'
const guard = new TokenGuard(store)
const token = await guard.authenticate(plainTextToken)
token?.name // => 'CLI'
token?.can('posts:read') // => true
await guard.check('bad|token') // => false
await guard.authenticateToken(plainTextToken) // => 1 (the owner's id, or null)authenticateToken() returns only the owner's id, which is convenient when your handler just needs to load the user. check() is a boolean shortcut.
A route middleware
Connect the guard to your routes with a middleware. This one authenticates the bearer token, optionally requires an ability, and attaches the token to the request so handlers can read the owner:
import { Response } from '@plinthjs/http'
import type { Middleware } from '@plinthjs/http'
import type { PersonalAccessToken } from '@plinthjs/api-tokens'
function tokenAuth(ability?: string): Middleware {
return async (request, next) => {
const bearer = request.bearerToken()
const token = bearer === undefined ? null : await guard.authenticate(bearer)
if (token === null) return Response.json({ message: 'Unauthenticated.' }, 401)
if (ability !== undefined && token.cant(ability)) {
return Response.json({ message: 'This token cannot do that.' }, 403)
}
return next(request.withAttribute('api.token', token))
}
}
router
.get('/api/posts', (request) => {
const token = request.attribute<PersonalAccessToken>('api.token')!
return Response.json({ owner: token.tokenableId })
})
.middleware(tokenAuth('posts:read'))
router.post('/api/posts', createPost).middleware(tokenAuth('posts:write'))A token with only posts:read gets a 200 on the first route and a 403 on the second; a request with no token gets 401. See Routing and Middleware.
Expiry and revoking
A token whose expiresAt is reached or passed stops authenticating. The guard takes an optional clock (epoch milliseconds), which also makes expiry easy to test:
let now = 1000
const guard = new TokenGuard(store, () => now)
const { plainTextToken } = await createToken(
store,
{ name: 'temp', expiresAt: 2000 },
{ now: () => now },
)
await guard.check(plainTextToken) // => true
now = 2000
await guard.check(plainTextToken) // => false (expiry is inclusive)accessToken.isExpired(now) performs the same check on a record. To revoke a token, delete it from the store; it stops working immediately:
await store.delete(accessToken.id)
await guard.check(plainTextToken) // => falseFor a "revoke all my tokens" button, delete each of await user.tokens() by id.
Writing a store
ArrayTokenStore does not survive a restart, so for production implement TokenStore against your database. The contract is four methods keyed by token id. Each may return its result directly or a promise (MaybePromise<T>), so a database client's async calls fit without any caching layer:
import type { PersonalAccessToken, TokenStore } from '@plinthjs/api-tokens'
class DatabaseTokenStore implements TokenStore {
async find(id: string): Promise<PersonalAccessToken | undefined> {
/* look up the row, then PersonalAccessToken.from(row) */
}
async save(token: PersonalAccessToken): Promise<void> {
/* upsert token.toAttributes() */
}
async delete(id: string): Promise<void> {
/* remove the row */
}
async all(): Promise<PersonalAccessToken[]> {
/* every stored token */
}
}PersonalAccessToken.from(attributes) rebuilds a record from a row and token.toAttributes() gives you a plain object to save. The attributes are id, name, tokenHash, abilities, createdAt, and the optional tokenableId, tokenableType, lastUsedAt, and expiresAt.
The guard, createToken() and hasApiTokens() await every store call, which is why they all return promises. ArrayTokenStore stays synchronous.
Testing
Pass seams to make issuing deterministic. createToken() accepts a third argument with now, generateId, and generateSecret:
const { plainTextToken } = await createToken(
store,
{ name: 'test' },
{ now: () => 1000, generateId: () => 'token-1', generateSecret: () => 'secret' },
)
plainTextToken // => 'token-1|secret'Combined with an ArrayTokenStore and a fake request, you can exercise the whole flow in-process, as the middleware example above does.
Related
- Authentication for session guards and the
AuthManager. - Authorization for deciding what a signed-in user may do, alongside token abilities.
- OAuth Server when third-party applications should obtain tokens on a user's behalf.