Node.js
Sign people in, host a SPA through a BFF, protect Node.js APIs, call APIs from workers with client credentials and receive webhooks with the Authio Node.js packages.
The Authio Node.js SDK is six packages on npm, in the @hyper.authio organization, version 0.15.0, for Node.js 20.19 or later, as ES modules and CommonJS. They read every endpoint from your realm’s discovery document and already understand Authio’s claims: scopes, the roles and permissions of each *_resource_access claim, groups, organizations and sign-in strength.
Pick a package
| Package | Use it for |
|---|---|
| @hyper.authio/express | An Express 4 or 5 API: bearer validation, guards for scopes, roles, permissions, groups, claims, organization and sign-in strength, and a signed webhook route. |
| @hyper.authio/server | An API on any other framework (Fastify, Hono, Nest, plain http): the same validation and rules as functions, plus webhooks, token forwarding and on-behalf-of. |
| @hyper.authio/client | Workers, CLIs and calls to Authio from anywhere, edge runtimes included: discovery, every token grant, introspection, revocation, UserInfo, a cached client-credentials fetch and webhook verification. |
| @hyper.authio/bff | The Express host of a SPA that signs in with Authio without tokens in the browser, with the same endpoints and cookie as Authio.AspNetCore.Bff. |
| @hyper.authio/admin | The Admin API, typed from its OpenAPI document, authenticated with an account credential; see The Admin API from the libraries. |
| @hyper.authio/testing | Tests: an in-memory realm on loopback that issues tokens, answers introspection and signs webhook deliveries. |
npm install @hyper.authio/express # an Express API (brings server and client)
npm install @hyper.authio/server # an API on another framework
npm install @hyper.authio/client # a worker, a CLI, or calls to Authio
npm install @hyper.authio/bff # the host of a SPA
npm install @hyper.authio/admin # the Admin API
npm install -D @hyper.authio/testing # testsPoint at your realm
Every package takes the realm’s issuer, {authority}/realms/{realm}, either as issuer or as authority plus realm. The discovery document is read from it, cached for an hour and refused if it names a different issuer; an http address is refused unless it is loopback. A client also takes its clientId and, in tokenEndpointAuthMethod, how it authenticates: client_secret_basic, client_secret_post, private_key_jwt or none for a public client. Left out, it follows the credentials given: a clientSecret means client_secret_basic, only a private key private_key_jwt, neither none.
AUTHIO_ISSUER=https://authio.api.hyperio.tech/realms/acme
AUTHIO_CLIENT_ID=orders-worker
AUTHIO_CLIENT_SECRET=YOUR_CLIENT_SECRETConfigure it like the client
The packages hard-code nothing the client configures in the console: each setting is an option, and an option left out is off. Authio refuses a request that does not match the client and accepts what the client does not require, such as PKCE sent to a client that does not ask for it, or a secret sent by a public client, which it ignores.
| In the console | Option | Left out |
|---|---|---|
PKCE, state and nonce | checks: 'pkce', 'state', 'nonce' (client, BFF) | Nothing generated or checked: a client that requires PKCE refuses the sign-in |
| PKCE methods | codeChallengeMethod: 'S256' or 'plain', one the client allows | S256 |
| Token endpoint auth method | tokenEndpointAuthMethod, matched exactly at the token, introspection, revocation and device endpoints | Follows the credentials given |
| ID token & userinfo signature | idTokenSignedResponseAlg (ID and logout tokens), userinfoSignedResponseAlg (signed UserInfo, left out: the ID token’s); HS with clientSecret | The asymmetric algorithms the realm publishes; HS refused |
| Access token signature | accessTokenSignedResponseAlg (server, express; one or several); HS with the clientSecret of client | The asymmetric algorithms the realm publishes; HS refused |
| Token encryption | clientEncryptionKey, encryptionAlgorithms, encryptionMethods | Nothing decrypted |
| Response mode | responseMode: 'query' or 'web_message' | Not sent; Authio answers in the query |
Renamed in 0.8.0, with no alias
clientAuthentication is now tokenEndpointAuthMethod. validAlgorithms is now idTokenSignedResponseAlg and userinfoSignedResponseAlg in the client and the BFF, and accessTokenSignedResponseAlg in the server and Express, which also accepts HS with the client secret. PKCE, state and nonce are no longer always on: list them in checks. The BFF no longer adds openid to scopes. See Token signing for the two signing settings.Protect an API
Register your API as a resource server, say https://api.example.com with the scopes orders:read and orders:write, and accept only its identifier as the audience. Clients ask for resource=https://api.example.com and their tokens carry it as aud.
import express from 'express'
import { authioBearer, requirePermission, requireScope } from '@hyper.authio/express'
const app = express()
app.use(
'/api',
authioBearer({
issuer: process.env.AUTHIO_ISSUER!,
audiences: 'https://api.example.com',
}),
)
app.get('/api/me', (req, res) => {
res.json(req.authio!.user)
})
app.get('/api/orders', requireScope('orders:read'), requirePermission('orders', 'read'), (req, res) => {
res.json([])
})
app.listen(3001)| Check | What authioBearer requires |
|---|---|
| Issuer and audience | Exactly the realm’s issuer, and one of audiences. A token addressed elsewhere is refused with an error_description that names the audience the API accepts. |
| Signature and lifetime | A key from the realm’s JWKS with an asymmetric algorithm (RS, PS, ES), re-read when a token names an unknown kid; exp and nbf with 30 seconds of clockSkew. HS only when accessTokenSignedResponseAlg names it, verified with the client secret. |
| Token type | The header typ must be at+jwt (RFC 9068, required since 0.9.0), so ID and refresh tokens, signed by the same keys, are refused. |
| Refusal | 401 with WWW-Authenticate: Bearer when there is no token, and Bearer error="invalid_token" with the reason when it is not valid. problemDetails: true adds an RFC 9457 body. |
Require scopes, roles, permissions and groups
Every guard is Express middleware and also a rule, so requireAuthio, allOf and anyOf combine them.
import {
anyOf,
requireAuthenticationLevel,
requireAuthio,
requireClaim,
requireGroup,
requireOrganization,
requirePermission,
requireRole,
requireScope,
} from '@hyper.authio/express'
// Any of the scopes; pass 'all' to need every one.
app.get('/api/orders/export', requireScope(['orders:read', 'orders:export'], 'all'), exportOrders)
// A role assigned to the person or one of their groups, not to everyone in the realm.
app.delete('/api/orders/:id', requireRole('orders-admin', { sources: ['user'] }), deleteOrder)
// A group (Group claim mapper) and a claim (any mapper, or the person's own claim).
app.get('/api/finance', requireGroup('finance'), requireClaim('department', 'finance'), report)
// A permission, and either a strong sign-in or the acme organization.
app.post(
'/api/payouts',
requireAuthio(requirePermission('payouts', 'create'), anyOf(requireAuthenticationLevel(2), requireOrganization('acme'))),
payout,
)| Guard | Passes when |
|---|---|
requireScope | Any (or, with 'all', every) scope is in scope. |
requireRole | The caller holds the role, case-insensitive. With sources, only roles from those claims count: user (the person and their groups), realm, client. Needs the roles scope. |
requirePermission | One of the caller’s roles grants the method on the resource, such as orders / write, optionally from given sources. |
requireGroup | A group claim (groups by default) holds the group. |
requireClaim | The claim is present, or holds one of the values you name. |
requireOrganization | org_id is present, or matches the alias or ID you name. |
requireAuthenticationLevel / requireAuthenticationMethod | acr reaches the level, or amr holds the method (mfa, otp, swk…). |
requireClient | client_id (or, without it, azp) is one of the clients — useful to admit one machine client. |
A missing scope answers 403 with WWW-Authenticate: Bearer error="insufficient_scope" and the scopes needed; a sign-in that is not strong enough answers 401 with insufficient_user_authentication (RFC 9470), so the client can send the person through a stronger sign-in. When another rule fails with it, the answer is that rule’s 403, since no stronger sign-in would satisfy it. Any other refusal is a plain 403.
Read the caller
req.authio.user is an AuthioUser, read the same way whether the token was validated locally or by introspection. It holds every form of permission Authio issues, and the raw claims for anything else. The access token itself is kept out of JSON and logs.
| Form | Comes from | Read it with |
|---|---|---|
| Scopes | scope, granted to the client | user.scopes, hasScope() |
| Roles and permissions | user_resource_access (the person, directly or through a group), realm_resource_access, client_resource_access, consumer_resource_access and secret_resource_access for machine credentials, each { role: { resource: [method] } } | user.roles, user.permissions, hasRole(), hasPermission(), user.resourceAccess per source |
| Groups and flat role names | Claim mappers with the Group or Role source, under the name you gave them (groups and role by default; change with groupClaims and roleClaims) | user.groups, hasGroup(), user.roles |
| Any other claim | Claim mappers (constant, user property) and the person’s own claims, in the access token | user.claims, claimValues(), hasClaim() |
| Organization and client | org_id, org_alias, client_id (or azp) | user.organizationId, user.organizationAlias, user.clientId |
| Roles held in the organization | org_roles, in an access token issued for an organization with the roles scope (a lightweight one leaves it to introspection) | user.organizationRoles (0.12.0); they hold in that organization alone, so user.roles, hasRole() and requireRole never read them |
| Sign-in strength | acr, amr, auth_time, idp | user.authenticationLevel, user.authenticationMethods, user.authenticatedAt |
| Delegation | act, delegation_id, delegation_chain | user.actor, user.delegated, user.delegationId, and user.delegationChain (0.12.0), every grant the token rests on, the first exchange’s first |
Other frameworks
@hyper.authio/server holds the same validation and rules without Express. A refusal is an AuthioBearerError (401) or an AuthioForbiddenError (403), each with the WWW-Authenticate value to send.
import { AuthioForbiddenError, authorize, createAuthioVerifier, requirePermission } from '@hyper.authio/server'
const verifier = createAuthioVerifier({
issuer: process.env.AUTHIO_ISSUER!,
audiences: 'https://api.example.com',
})
export async function caller(authorization: string | undefined) {
// Throws AuthioBearerError: answer 401 with error.wwwAuthenticate.
const user = await verifier.verifyAuthorizationHeader(authorization)
const refusal = authorize(user, requirePermission('orders', 'read'))
// AuthioForbiddenError: answer 403, with error.wwwAuthenticate when it has one.
if (refusal) throw new AuthioForbiddenError(refusal)
return user
}Notice revocations before the token expires
A locally validated token stays valid until it expires, even after its session ended or its user was suspended. introspection: 'activeCheck' also asks Authio whether the token is still active, cached per token for 30 seconds; 'introspectionOnly' validates by introspection alone, for reference or encrypted tokens and for access tokens another client signs with HS. Both need the API’s confidential client, the one the resource server names as its introspection client: Authio reports a token addressed to a resource server as active only to that client.
app.use(
'/api',
authioBearer({
issuer: process.env.AUTHIO_ISSUER!,
audiences: 'https://api.example.com',
introspection: 'activeCheck',
client: { clientId: process.env.AUTHIO_CLIENT_ID!, clientSecret: process.env.AUTHIO_CLIENT_SECRET },
}),
)Lightweight and reference access tokens
The client’s Access Token Format decides the introspection. A Lightweight token is a JWT without the roles, the permissions, the plan, the profile and the email. From 0.10.0, with introspection: 'activeCheck', the caller is read from the token plus the claims of the introspection answer the token does not carry, so requireRole, requirePermission and user.roles work as they do with a complete JWT; a claim the token carries keeps its signed value. An Opaque (reference) token is only readable through introspection: use 'introspectionOnly'. With 'none', a lightweight token is still valid but arrives without roles, and the library does not guess the format from the claims a token lacks.
app.use(
'/api',
authioBearer({
issuer: process.env.AUTHIO_ISSUER!,
audiences: 'https://api.example.com',
// Lightweight: 'activeCheck' or 'introspectionOnly'. Opaque: 'introspectionOnly'.
introspection: 'activeCheck',
client: { clientId: process.env.AUTHIO_CLIENT_ID!, clientSecret: process.env.AUTHIO_CLIENT_SECRET },
}),
)On the BFF, accessTokenClaims: 'introspection' reads the session’s roles, permissions and organization from the introspection of the access token, at sign-in and on every refresh; an opaque token is introspected either way. A reference refresh token changes nothing: no package reads the refresh token. The table for every library, and what happens when introspection fails, are in Integrate with the libraries.
Call an API from a worker
clientCredentialsFetch is a fetch that sends a client-credentials token for the scopes and resource you name. The token is cached and renewed a minute before it expires, with one request for concurrent callers; on a 401 it is dropped and the call retried once.
import { createAuthioClient } from '@hyper.authio/client'
const authio = createAuthioClient({
issuer: process.env.AUTHIO_ISSUER!,
clientId: process.env.AUTHIO_CLIENT_ID!,
clientSecret: process.env.AUTHIO_CLIENT_SECRET,
})
const ordersFetch = authio.clientCredentialsFetch({
scopes: 'orders:read',
resource: 'https://api.example.com',
})
const response = await ordersFetch('https://api.example.com/api/orders')To keep the secret off the wire, register the client’s public key and set tokenEndpointAuthMethod: 'private_key_jwt' with clientPrivateKey (PEM or JWK) or clientPrivateKeyPath, and clientKeyId: the client signs a short-lived assertion for every request. The same client covers the other grants: authio.tokens.authorizationCode, refresh (store the rotated refresh token it returns), exchange for on-behalf-of, deviceAuthorization and pollDevice for the device flow, plus introspect, revoke and userInfo.
Call another API on behalf of the caller
import { createAuthioClient } from '@hyper.authio/client'
import { createOnBehalfOf } from '@hyper.authio/server'
const billing = createOnBehalfOf({
client: createAuthioClient({ issuer, clientId, clientSecret }),
resource: 'https://billing.example.com',
scopes: 'invoices:read',
})
app.get('/api/invoices', async (req, res) => {
const response = await billing.fetch(req.authio!.user)('https://billing.example.com/invoices')
res.status(response.status).json(await response.json())
})The caller’s token is exchanged (RFC 8693) once per token, resource and scopes and cached; the new token keeps the person as sub and names your API in act. To pass the caller’s token on unchanged to an API that accepts the same audience, use createForwardingFetch(user).
Sign people in to a server-rendered app
A web app with its own server (Express, Fastify, Hono) signs people in with @hyper.authio/client: createAuthorizationUrl builds the authorization request and the transaction to keep, and handleAuthorizationCallback checks state and the RFC 9207 iss, redeems the code with the PKCE verifier and validates the ID token. Register a client of the kind Web application with http://localhost:5090/callback in Redirect URIs, http://localhost:5090/ in Post-logout redirect URIs and http://localhost:5090/backchannel-logout as the Back-channel logout URI, and put its values in .env as above.
npm install express @hyper.authio/client @hyper.authio/expresschecksmirrors the client: listpkcewhen the client requires PKCE, as a Web application does, plusstateandnonce. Left out, nothing is generated or checked.createAuthorizationUrlalso takesresource,organization,prompt,maxAge,acrValues,loginHint,uiLocalesandidpHint, the alias of an identity provider to go straight to.popup: trueruns the sign-in in a popup (display=popup,response_mode=web_message).acrValuesasks for a level and does not guarantee one: readidToken.acrafter the callback and refuse a sign-in below the level you need.- A callback that is not for the transaction throws
AuthioCallbackError(state_mismatch,issuer_mismatch,missing_issuer,missing_code); an error Authio sent back, such aslogin_requiredafterprompt: 'none', throwsAuthioProtocolError. - Sessions live in memory here: keep them in your own store in production. Ask for
offline_accessand callauthio.tokens.refreshto renew the access token, storing the rotated refresh token it returns.
Sign a SPA in through a BFF
@hyper.authio/bff is the Express host of a SPA that signs in without ever holding a token: it runs the code flow with PKCE as a confidential client, keeps the tokens server-side and refreshes them, and the browser only holds an HttpOnly __Host-authio cookie. It has the same endpoints, cookie and option names as `Authio.AspNetCore.Bff`. Register a client of the kind Web application with https://app.example.com/signin-oidc in Redirect URIs, https://app.example.com/signout-callback-oidc in Post-logout redirect URIs, https://app.example.com/bff/backchannel-logout as the Back-channel logout URI, and the scopes openid profile email offline_access, plus roles with requestRoles and your API scopes.
import express from 'express'
import { authioBff } from '@hyper.authio/bff'
const app = express()
const bff = authioBff({
issuer: process.env.AUTHIO_ISSUER!,
clientId: process.env.AUTHIO_CLIENT_ID!,
clientSecret: () => process.env.AUTHIO_CLIENT_SECRET!,
checks: ['pkce', 'state', 'nonce'],
codeChallengeMethod: 'S256',
cookieSecret: process.env.BFF_COOKIE_SECRET!,
requestRoles: true,
resource: 'https://api.example.com',
})
app.use(bff)
app.use('/api/orders', bff.remoteApi('https://api.example.com/orders'))
app.use(express.json())
app.get('/api/me', bff.api(), (req, res) => res.json({ name: req.authioBff!.claims.name }))
app.use(express.static('dist'))
app.listen(5000)cookieSecrethas 32 characters or more; an array rotates it. Mountbff.remoteApibefore any body parser, so the body is streamed through. Behind a reverse proxy, setapp.set('trust proxy', 1), orredirectUriandpostLogoutRedirectUri./bff/logintakesreturnUrl(local only),organization,prompt,login_hint,ui_locales,max_ageandresource./bff/useranswers the session’s claims, oneroleand onepermissionper grant,bff:session_expires_inandbff:logout_url, or401without a session, never a redirect.bff.remoteApi(url, { tokenMode })attaches the person’s token (user, the default), that token when there is one (userOrNone) or a client-credentials token of the BFF (clientCredentials).bff.userFetch(req, res, { resource })hands the person’s token to your own code.- Left out,
scopesisopenid profile email offline_access, plusroleswithrequestRoles. A list you set is sent as it is: keepopenidin it. - The SPA uses no Authio library, since no token goes through it: the
api.tsabove, afetchto its own host with the session cookie and theX-CSRF: 1header, is enough.
Receive webhooks
import { authioWebhooks } from '@hyper.authio/express'
// Before express.json(): the signature is checked over the raw body.
app.post(
'/webhooks/authio',
authioWebhooks({ secret: process.env.AUTHIO_WEBHOOK_SECRET })
.on('user_deleted', async (event) => forget(event.data.id))
.on('*', (event) => console.log(event.type)),
)The route verifies X-Authio-Signature against every configured secret (pass secrets while you rotate one), refuses a signature older than five minutes, and acknowledges a redelivery of the same X-Authio-Event-Id without running the handlers again. It answers 200 handled or duplicate, 400 unreadable, 401 bad signature, 413 too large and 500 when a handler throws, which lets Authio deliver again. See Webhooks for the events.
Test without a realm
import { FakeAuthio } from '@hyper.authio/testing'
const authio = await FakeAuthio.start({ realm: 'acme' })
const token = await authio.issueAccessToken({
sub: 'u-1',
audience: 'https://api.example.com',
scope: 'orders:read',
claims: { user_resource_access: { clerk: { orders: ['read'] } }, groups: ['finance'] },
})
// Point the API at authio.issuer, call it with the token, then:
await authio.close()The fake serves discovery, JWKS, every grant, introspection, revocation and UserInfo on loopback, records each request, and can answer with scripted errors. createWebhookDelivery builds a signed delivery for the webhook route.