Skip to content

JS Server SDK Overview

@authrim/server is Authrim’s server-side SDK for resource servers. It validates JWT access tokens, verifies DPoP proofs, manages issuer-scoped JWKS key sets, and provides framework middleware for popular Node.js frameworks. It also exposes server-side helpers for introspection, revocation, Native SSO device secrets, canonical Step-Up, customer profile protected resources, cookie-session CSRF, and back-channel logout.

The following diagram shows where @authrim/server fits in the OAuth 2.0 architecture:

sequenceDiagram
    participant Client as Client App<br>(@authrim/web or<br>@authrim/core)
    participant AuthServer as Authrim<br>Authorization Server
    participant Resource as Resource Server<br>(@authrim/server)

    Client->>AuthServer: 1. Authorization Request
    AuthServer-->>Client: 2. Access Token (JWT)
    Client->>Resource: 3. API Request + Access Token
    Resource->>AuthServer: 4. Fetch JWKS (cached)
    Resource->>Resource: 5. Validate Token
    Resource-->>Client: 6. Protected Resource

The SDK handles steps 4 and 5 automatically, fetching and caching the authorization server’s public keys, then validating token signatures and claims.

Export PathPurposeKey Exports
@authrim/serverMain entry — client factory, types, validators, JWKS, Step-Up, customer profiles, session utilitiescreateAuthrimServer, AuthrimServer, StepUpClient, CustomerProfileClient, BackChannelLogoutValidator
@authrim/server/providersProvider interfaces and utilitiesCryptoProvider, HttpProvider, ClockProvider, CacheProvider
@authrim/server/adapters/expressExpress middlewareauthrimMiddleware, authrimOptionalMiddleware
@authrim/server/adapters/fastifyFastify hooks and pluginsauthrimPreHandler, authrimPlugin, authrimOptionalPreHandler, authrimOptionalPlugin
@authrim/server/adapters/honoHono middlewareauthrimMiddleware, authrimOptionalMiddleware, getAuth, getAuthTokenType
@authrim/server/adapters/koaKoa middlewareauthrimMiddleware, authrimOptionalMiddleware
@authrim/server/adapters/nestjsNestJS guard and utilitiescreateAuthrimGuard, createAuthrimOptionalGuard, getAuthFromRequest, getAuthTokenTypeFromRequest
  • JWT Access Token Validation — Signature verification, claims validation (iss, aud, exp, nbf, iat), scope enforcement
  • DPoP Proof Validation (RFC 9449) — Sender-constrained token verification with JWK Thumbprint binding
  • JWKS Management — Auto-discovery, caching with Cache-Control, key rotation support, single-flight fetch
  • Multi-Issuer Resource Servers — Allow-list multiple issuers and configure issuer-specific JWKS, introspection, revocation, and Step-Up endpoints
  • Token Introspection (RFC 7662) — Query the authorization server for opaque token status
  • Token Revocation (RFC 7009) — Revoke tokens at the authorization server
  • Native SSO Device Secret Operations — Introspect and revoke device_secret values without logging the raw secret
  • Canonical Step-Up — Start, inspect, complete, resend, and cancel Step-Up actions from server code
  • Customer Profile Protected Resource API — Read profiles with elevation grants and perform delegated writes
  • Cookie Session Security — Direct Auth artifact redemption helpers, double-submit CSRF helpers, and cookie attribute resolution
  • Back-Channel Logout (OIDC 1.0) — Validate logout tokens from the authorization server
  • Framework Middleware — Ready-to-use adapters for Express, Fastify, Hono, Koa, and NestJS
  • Security Hardened — Timing-safe comparisons, alg:none rejection, SSRF protection, JWT size limits
FamilyAlgorithms
RSA PKCS#1 v1.5RS256, RS384, RS512
RSA-PSSPS256, PS384, PS512
ECDSAES256, ES384, ES512
EdDSAEdDSA

@authrim/server runs on any JavaScript runtime with standard Web Crypto API support:

  • Node.js 18+
  • Bun
  • Deno
  • Cloudflare Workers
  • Vercel Edge Runtime

@authrim/server validates access tokens in three phases:

  1. Initialization — On startup, the SDK fetches the authorization server’s OIDC Discovery document and JWKS (public keys). These are cached in memory.
  2. Token Validation — For each incoming request, the SDK parses the JWT, selects the correct signing key by kid, verifies the cryptographic signature, and validates all standard claims (issuer, audience, expiration, etc.).
  3. Ongoing Key Management — The SDK monitors key freshness, handles Cache-Control headers, and automatically refetches keys when a new kid is encountered (key rotation).

All of this is encapsulated in two method calls: init() at startup and validateToken() per request.

MethodDescription
init()Fetch OIDC Discovery document and JWKS. Call once at startup.
validateToken(token)Validate a JWT access token using the configured validation rules.
validateDPoP(proof, options)Validate a DPoP proof JWT (RFC 9449).
introspect(token, tokenTypeHint?, issuerOptions?)Query the authorization server for token status (RFC 7662).
revoke(token, tokenTypeHint?, issuerOptions?)Revoke a token at the authorization server (RFC 7009).
introspectDeviceSecret(deviceSecret, issuerOptions?)Query Native SSO device_secret status.
revokeDeviceSecret(deviceSecret, issuerOptions?)Revoke a Native SSO device_secret.
stepUp.start() / startStepUp()Start a canonical Step-Up action from a step_up_token.
customerProfiles.getWithElevationGrant()Read a customer profile with an elevation grant.
customerProfiles.updateDelegated()Perform a delegated customer profile write.
invalidateJwksCache()Force the next validation to refetch the JWKS.
import { createAuthrimServer } from '@authrim/server';
const authrim = createAuthrimServer({
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
tokenValidation: {
requiredScopes: ['profile:read'],
requireTenantClaim: true,
},
});
// Initialize once at startup (fetches JWKS)
await authrim.init();
// Validate an incoming access token
const result = await authrim.validateToken(bearerToken);
if (result.error) {
throw new Error(result.error.message);
}
console.log(result.data.claims.sub); // Subject (user ID)
console.log(result.data.claims.scope); // Granted scopes
console.log(result.data.issuer); // Validated issuer
console.log(result.data.tenantId); // Tenant claim when present
console.log(result.data.tokenType); // 'Bearer' or 'DPoP'
console.log(result.data.expiresIn); // Seconds until expiration

Instead of calling validateToken() manually, use a framework adapter for automatic token extraction and validation:

import express from 'express';
import { createAuthrimServer } from '@authrim/server';
import { authrimMiddleware } from '@authrim/server/adapters/express';
const app = express();
const authrim = createAuthrimServer({
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});
await authrim.init();
// Protected route — token validated automatically
app.get('/api/me', authrimMiddleware(authrim), (req, res) => {
res.json({ userId: req.auth.claims.sub });
});
// Protected route with required scopes
app.delete('/api/users/:id', authrimMiddleware(authrim, { requiredScopes: ['admin:write'] }), (req, res) => {
res.json({ deleted: true });
});
app.listen(3000);
ScenarioPackageDescription
Validate tokens on your API@authrim/serverThis SDK — for resource servers
Log users in via browser@authrim/webBrowser-based OAuth/OIDC flows
Full-stack SvelteKit auth@authrim/sveltekitServer hooks + Svelte stores
Build a custom OAuth client@authrim/corePlatform-agnostic protocol library
SpecificationRFCCoverage
JSON Web Token (JWT)RFC 7519Token parsing and claims validation
JSON Web Key (JWK)RFC 7517JWKS fetch, key import, key selection
JWK ThumbprintRFC 7638DPoP thumbprint computation and binding
Token IntrospectionRFC 7662Full introspection client
Token RevocationRFC 7009Full revocation client
DPoPRFC 9449Stateless proof validation, thumbprint binding
OIDC Core 1.0ID token and claims validation
OIDC Back-Channel Logout 1.0Logout token validation