OAuth Server
Introduction
When other applications need to call your API on behalf of your users, or when your own mobile app and single-page app need tokens, you become an OAuth 2.0 authorization server. @plinthjs/oauth-server implements the server side: client registration, four grants (authorization_code with PKCE, client_credentials, refresh_token, and password), scopes, and the revoke and validation operations.
pnpm add @plinthjs/oauth-serverThe package contains the protocol logic and no routes. An AuthorizationServer exposes async methods that take the request parameters and return a promise of the result or reject with OAuthError; you call them from your own routes, as shown below. All persistence goes through store interfaces that may be synchronous or asynchronous, with in-memory implementations included. Time and id generation can be replaced, so everything is testable.
INFO
Tokens and authorization codes are opaque strings, not JWTs. Each looks like id.secret, shown to the client once, with only a SHA-256 hash of the secret stored. This avoids a signing dependency, but it also means only this server can validate a token: resource servers must call back into the same stores. Client secrets are stored hashed the same way.
If you only need simple personal access tokens, API Tokens is much smaller. If you want to sign in with someone else's provider, see OAuth Client.
Setting up the server
An AuthorizationServer needs four stores and a scope registry:
import {
ArrayAuthCodeStore,
ArrayClientStore,
ArrayRefreshTokenStore,
ArrayTokenStore,
AuthorizationServer,
ResourceServer,
ScopeRegistry,
} from '@plinthjs/oauth-server'
const clients = new ArrayClientStore()
const tokens = new ArrayTokenStore()
const scopes = new ScopeRegistry()
.define('users:read', 'Read users')
.define('users:write', 'Write users')
const server = new AuthorizationServer({
clients,
tokens,
refreshTokens: new ArrayRefreshTokenStore(),
authCodes: new ArrayAuthCodeStore(),
scopes,
ttl: { accessTokenTtlSeconds: 900 },
})
const resource = new ResourceServer({ tokens })The optional ttl sets the lifetimes: access tokens default to one hour, refresh tokens to 30 days, and authorization codes to 10 minutes (accessTokenTtlSeconds, refreshTokenTtlSeconds, authCodeTtlSeconds). The optional seams option replaces now, generateId, and generateSecret for deterministic tests. The array stores keep everything in memory; in production, implement ClientStore, TokenStore, RefreshTokenStore, and AuthCodeStore against your database (see the end of this page); they may return promises.
Scopes
A scope is a named permission that a client may ask for and a token may carry. Register every scope with the registry, with a description you can show on a consent screen:
scopes.has('users:read') // => true
scopes.all() // => [{ id: 'users:read', description: 'Read users' }, ...]
scopes.ids() // => ['users:read', 'users:write']The wildcard scope * always exists. A client that is allowed * may request any registered scope or * itself. Requesting no scope grants the client's full allowed set. Requesting an unknown scope, or one the client is not permitted, fails with an invalid_scope error.
Registering clients
A client is an application that uses your server. Register each one as a Client and save it in the client store. Secrets are never stored: you hash them with hashClientSecret() and keep only the hash.
import { randomBytes } from 'node:crypto'
import { Client, hashClientSecret } from '@plinthjs/oauth-server'
const secret = randomBytes(24).toString('hex') // show this to the developer once
await clients.save(
Client.from({
id: 'billing-service',
name: 'Billing service',
secretHash: hashClientSecret(secret),
redirectUris: [],
grantTypes: ['client_credentials'],
scopes: ['users:read'],
confidential: true,
}),
)The fields:
| Field | Meaning |
|---|---|
id | The public client id. |
secretHash | Hash of the secret. Omit it for public clients. |
redirectUris | The exact callback URLs this client may use. Required for authorization_code. |
grantTypes | Which grants this client may use. |
scopes | The most the client may request. ['*'] allows everything. |
confidential | true for server-side clients that can keep a secret, false for browser and mobile apps. |
revoked | Set to true to disable a client. |
Confidential clients must present their secret on every token request. Public clients must not; presenting a secret is an error, and they are required to use PKCE for the authorization code grant. A client that is revoked, unknown, or not allowed the grant it asks for is rejected.
Issuing tokens
server.issueToken(grantType, params) handles every token request. It takes the grant_type and the request parameters (client id, secret, code, and so on) as a string map, and resolves to the issued tokens or rejects with an OAuthError:
const issued = await server.issueToken('client_credentials', {
client_id: 'billing-service',
client_secret: secret,
scope: 'users:read',
})
issued.tokenType // => 'Bearer'
issued.accessToken // => 'abc...def.ghi...jkl' (shown to the client once)
issued.expiresIn // => 900
issued.scope // => 'users:read'
issued.refreshToken // => undefined (client_credentials issues none)IssuedTokens has tokenType, accessToken, refreshToken (when the grant issues one), expiresIn in seconds, scope as a space-separated string, and accessTokenRecord, the stored record.
Client credentials
For server-to-server calls with no user. The token has no userId, and no refresh token is issued. The client authenticates with its id and secret, and may request scopes within its allowed set.
Authorization code with PKCE
This is the grant for web, single-page, and mobile apps that act for a signed-in user. It has two steps. First the user approves the request on your site, and the server issues a short-lived code. Then the client exchanges the code for tokens.
Step 1: the authorize endpoint. validateAuthorizationRequest() checks the query parameters (response type, client, redirect URI, scopes, and PKCE) and returns a validated request you can use to render a consent screen. After the signed-in user decides, completeAuthorizationRequest() returns the URL to redirect them to:
import { Response } from '@plinthjs/http'
import { OAuthError } from '@plinthjs/oauth-server'
router.get('/oauth/authorize', async (request) => {
const params = request.queryAll()
const authRequest = await server.validateAuthorizationRequest(params)
// Show a consent screen listing authRequest.client.name and authRequest.scopes.
// Keep authRequest on the server side (for example in the session) until the user answers.
return Response.json({ client: authRequest.client.name, scopes: authRequest.scopes })
})
router.post('/oauth/authorize', async (request) => {
const authRequest = pendingRequestFromSession(request)
const { redirectTo } = await server.completeAuthorizationRequest({
request: authRequest,
userId: String(currentUserId(request)),
approved: request.boolean('approve'),
})
return Response.redirectTo(redirectTo)
})When approved, the redirect carries code and your original state (https://spa.test/callback?code=...&state=xyz). When denied, it carries error=access_denied. The redirect URI must exactly match one registered for the client; if the client has exactly one registered URI, redirect_uri may be omitted.
The authorize endpoint also requires the user to be signed in. Put your authentication middleware in front of it (see Authentication).
Step 2: the token endpoint. The client posts the code with its PKCE verifier. A public client generates a random verifier and sends its SHA-256 code_challenge with the authorize request; deriveCodeChallenge() computes the same value on the server side for comparison:
const issued = await server.issueToken('authorization_code', {
code,
client_id: 'spa',
redirect_uri: 'https://spa.test/callback',
code_verifier: verifier,
})
issued.scope // => 'users:read'
issued.refreshToken // => 'a refresh token'
issued.accessTokenRecord.userId // => '1'The code is single use and is consumed before tokens are issued, so replaying it fails with invalid_grant ("The authorization code has already been used."). The server checks that the code belongs to the client, that the redirect URI matches, that it has not expired, and that the verifier hashes to the stored challenge. Only the S256 challenge method is supported. Public clients must send a code_challenge; confidential clients may as well.
Refresh tokens
When an access token expires, the client trades its refresh token for a new pair. Refresh tokens are rotated: the presented refresh token and its access token are revoked, and a new pair is issued, so a refresh token works once.
const refreshed = await server.issueToken('refresh_token', {
refresh_token: issued.refreshToken!,
client_id: 'spa',
})
await resource.validate(issued.accessToken) // => null (the old access token is revoked)A scope parameter may narrow the original scopes but never widen them. A refresh token that is expired, revoked, already used, or issued to another client fails with invalid_grant.
Password grant
The password grant exchanges a username and password for tokens directly. It is disabled unless you give the server a verifyCredentials function that returns the user id for valid credentials, or null:
const server = new AuthorizationServer({
clients,
tokens,
refreshTokens,
authCodes,
scopes,
verifyCredentials: (username, password) =>
username === 'ada@example.com' && checkPassword(password) ? '1' : null,
})
const issued = await server.issueToken('password', {
client_id: 'mobile',
client_secret: 'mobile-secret',
username: 'ada@example.com',
password: 'secret',
scope: 'users:read',
})Without verifyCredentials, a password request fails with unsupported_grant_type. The password grant gives the client the user's raw password, so only enable it for first-party applications you control. The verifier may be synchronous or return a promise, so it can query your user store directly.
Exposing the token endpoint
handleTokenRequest(server, { headers, body }) runs a whole token request: it reads grant_type, applies client authentication, issues the tokens, and returns a plain { status, headers, body } with the RFC 6749 JSON. Errors become the standard { error, error_description } body with the right status, and every response carries Cache-Control: no-store. Wire it into a route:
import { handleTokenRequest } from '@plinthjs/oauth-server'
router.post('/oauth/token', async (request) => {
const result = await handleTokenRequest(server, {
headers: { authorization: request.header('Authorization') ?? undefined },
body: request.all() as Record<string, string>,
})
return Response.json(result.body, result.status).withHeaders(result.headers)
})An OAuthError is HTTP-aware: it has a status (400 for invalid_request, invalid_grant, invalid_scope, unauthorized_client, unsupported_grant_type, and unsupported_response_type; 401 for invalid_client; 403 for access_denied; 500 for server_error), a code, a description, and toResponseBody(). When you call the server directly instead of through the helper, oauthErrorResponse(error) produces the same response for a caught OAuthError. A failed client login, for example:
try {
await server.issueToken('client_credentials', {
client_id: 'billing-service',
client_secret: 'wrong',
})
} catch (error) {
const body = (error as OAuthError).toResponseBody()
// body => { error: 'invalid_client', error_description: 'Client authentication failed.' }
// (error as OAuthError).status => 401
}Client authentication
Clients may authenticate with HTTP Basic (Authorization: Basic base64(client_id:client_secret), RFC 6749 section 2.3.1) or with client_id and client_secret body parameters. Both go through the same validation. The Basic credentials are form-decoded before use. If a request carries both, the values must agree; a header that names one client and a body that names another is rejected with invalid_request, and a malformed Basic header with invalid_client (a 401 that includes a WWW-Authenticate: Basic challenge). When calling server.issueToken(grantType, params, authorization) yourself, pass the raw header value as the third argument.
Protecting your API
A ResourceServer validates bearer tokens against the same token store. validate() resolves to the active access token or null; validateForScope() also checks a scope:
const token = await resource.validate(issued.accessToken)
token?.scopes // => ['users:read']
token?.userId // => '1' for user-bound tokens, undefined for client_credentials
await resource.validateForScope(issued.accessToken, 'users:read') // => true
await resource.validateForScope(issued.accessToken, 'users:write') // => falseA token that is expired, revoked, unknown, or malformed gives null. Connect it to your routes with a middleware:
import type { Middleware } from '@plinthjs/http'
const requireScope =
(scope: string): Middleware =>
async (request, next) => {
const bearer = request.bearerToken()
const token = bearer === undefined ? null : await resource.validate(bearer)
if (token === null) return Response.json({ message: 'Unauthenticated.' }, 401)
if (token.cant(scope)) return Response.json({ message: 'Insufficient scope.' }, 403)
return next(request.withAttribute('oauth.token', token))
}
router.get('/api/users', listUsers).middleware(requireScope('users:read'))token.can(scope) and token.cant(scope) treat a * scope as granting everything. For user-bound tokens, token.userId identifies the user. Expiry is checked with the clock you give the ResourceServer (now, default Date.now).
Revoking tokens
revokeToken(token, hint?) revokes an access token or a refresh token, together with its counterpart. It resolves to true when something was revoked and false for unknown or malformed values, which is what the standard revocation endpoint should report without leaking details. The optional hint ('access_token' or 'refresh_token') only chooses which kind to try first:
await server.revokeToken(issued.accessToken) // => true
await resource.validate(issued.accessToken) // => null
await server.revokeToken('junk') // => falseStoring data in your database
The in-memory stores implement four small interfaces keyed by id: ClientStore, TokenStore, RefreshTokenStore, and AuthCodeStore. Each has find, save, delete, and all, and every method may return the value directly or a promise of it (MaybePromise<T>). The server awaits every store call, so a database driver works as is. Records (Client, AccessToken, RefreshToken, AuthCode) expose toAttributes(), and the constructors rebuild them from stored rows:
import { AccessToken } from '@plinthjs/oauth-server'
import type { TokenStore } from '@plinthjs/oauth-server'
class DatabaseTokenStore implements TokenStore {
async find(id: string): Promise<AccessToken | undefined> {
const row = await db.table('oauth_access_tokens').where('id', id).first()
return row === undefined ? undefined : new AccessToken(rowToAttributes(row))
}
async save(token: AccessToken): Promise<void> {
await db.table('oauth_access_tokens').upsert(token.toAttributes())
}
async delete(id: string): Promise<void> {
await db.table('oauth_access_tokens').where('id', id).delete()
}
async all(): Promise<AccessToken[]> {
return (await db.table('oauth_access_tokens').get()).map(
(row) => new AccessToken(rowToAttributes(row)),
)
}
}Keep the same semantics as the array stores (insert or replace on save, no error when deleting a missing id).
Testing
Everything runs in memory. Use the seams option for deterministic ids and a fixed clock, and the array stores for state:
const server = new AuthorizationServer({
clients,
tokens,
refreshTokens: new ArrayRefreshTokenStore(),
authCodes: new ArrayAuthCodeStore(),
scopes,
seams: { now: () => 1_700_000_000_000 },
})Related
- API Tokens for simple personal access tokens.
- OAuth Client for signing users in with an external provider.
- Authorization for fine-grained checks beyond token scopes.