fastify-bit-oidc-auth
v1.0.0
Published
A reusable Fastify OIDC authentication and RBAC library
Maintainers
Readme
fastify-bit-oidc-auth
A reusable, production-ready Fastify middleware suite designed to handle OIDC (OpenID Connect) authentication, Role-Based Access Control (RBAC), and Multi-Tenant scoping in a secure, "default-deny" manner.
Installation
npm install fastify-bit-oidc-authEnsure you have your peer dependencies installed (Fastify v4 or v5):
npm install fastifyFeatures
- Stateless JWT Validation: Validates OIDC Bearer tokens using remote JWKS (
jose) with customizable caching. - RBAC (Role-Based Access Control): Restricts endpoints to specific user roles.
- Multi-Tenant Isolation: Enforces tenant scoping via
organization_idclaim, with support for cross-tenant bypass for super administrator roles.
Usage
import Fastify from 'fastify';
import {
createAuthMiddleware,
requireRoles,
createTenantMiddleware
} from 'fastify-bit-oidc-auth';
const fastify = Fastify({ logger: true });
// 1. Initialize authentication middleware
const authMiddleware = createAuthMiddleware({
jwksUri: 'https://keycloak.example.com/realms/myrealm/protocol/openid-connect/certs',
issuer: 'https://keycloak.example.com/realms/myrealm',
audience: 'my-client-id', // Optional: Verifies 'azp' claim
rolesClaim: 'my_custom_roles_claim' // Optional: Fallback is 'realm_access.roles'
});
// 2. Initialize tenant separation middleware
const tenantMiddleware = createTenantMiddleware({
superAdminRole: 'platform_admin' // Optional: Role that bypasses tenant scoping
});
// 3. Register protected routes
fastify.get('/api/dashboard', {
preHandler: [
authMiddleware,
requireRoles('org_admin', 'campaign_manager'),
tenantMiddleware
]
}, async (request, reply) => {
// Safe to access:
const user = request.user; // { id, email, roles, organization_id }
return {
message: 'Hello secure world!',
organization: user.organization_id
};
});
fastify.listen({ port: 3000 });Configuration Options
AuthConfig
jwksUri(string, required): URI of your Identity Provider's certificate endpoint.issuer(string, required): Expected token issuer.audience(string, optional): Expected client ID (azpclaim).rolesClaim(string, optional): Key inside token containing the user roles array.jwksCacheTtlMs(number, optional): Cache duration of JWKS (default: 1 hour).
TenantConfig
superAdminRole(string, optional): Role name that bypasses tenant checks (default:platform_admin).
License
MIT
