Skip to content

Authentication -- Setup & Configuration

JWT authentication with JWS (symmetric) and JWKS (asymmetric) standards, optional AES-encrypted payloads, Basic HTTP authentication, multi-strategy support, and built-in auth controller

Quick Reference

ItemValue
Package@venizia/ignis
ClassAuthenticateComponent
RuntimesBoth

Key Components

ComponentPurpose
AuthenticateComponentMain component registering auth services and controllers
AuthenticationStrategyRegistrySingleton managing available auth strategies
JWSAuthenticationStrategyJWT verification using symmetric JWSTokenService (HS256)
JWKSIssuerAuthenticationStrategyJWT verification using asymmetric JWKSIssuerTokenService (ES256/RS256/EdDSA)
JWKSVerifierAuthenticationStrategyJWT verification via remote JWKS URL
BasicAuthenticationStrategyBasic HTTP authentication using BasicTokenService
AbstractBearerTokenServiceBase class for all Bearer token services (JWS, JWKS Issuer, JWKS Verifier)
JWSTokenServiceSymmetric JWT — sign, verify, optional AES encrypt/decrypt
JWKSIssuerTokenServiceAsymmetric JWT — sign with private key, verify with public key, serve JWKS endpoint
JWKSVerifierTokenServiceAsymmetric JWT — verify-only via remote JWKS URL
BasicTokenServiceExtract and verify Basic auth credentials
JWKSControllerServes /.well-known/jwks.json-style endpoint at /certs
IAuthServiceInterface for custom auth implementation (sign-in, sign-up)
defineAuthControllerFactory function for creating custom auth controllers
AbstractJWKSTokenServiceBase class for JWKS services with lazy initialization and retry-on-failure
authenticateStandalone middleware function using AuthenticationProvider to create auth middleware

JOSE Standards

The authentication module supports two JOSE (JSON Object Signing and Encryption) standards:

StandardClassUse CaseSigningKey Type
JWSJWSTokenServiceSingle-service apps where the same service signs and verifiesHS256 (symmetric)Shared secret (jwtSecret)
JWKS (Issuer)JWKSIssuerTokenServiceMulti-service / microservice architectures where one service issues tokensES256 / RS256 / EdDSA (asymmetric)Private key (sign) + Public key (verify)
JWKS (Verifier)JWKSVerifierTokenServiceServices that only verify tokens issued by another serviceN/A (verify-only)Remote JWKS URL

Environment Variables

VariablePurposeRequired
APP_ENV_JWT_SECRETSign and verify JWT signature (JWS only)Required for JWS
APP_ENV_APPLICATION_SECRETAES-encrypt JWT payload fieldsOptional
APP_ENV_JWT_EXPIRES_INToken expiration (seconds)Required
APP_ENV_JWKS_ALGORITHMJWKS signing algorithm (e.g., ES256)Required for JWKS
APP_ENV_JWKS_KEY_DRIVERKey source: text or fileRequired for JWKS
APP_ENV_JWKS_KEY_FORMATKey format: pem or jwkRequired for JWKS
APP_ENV_JWKS_PRIVATE_KEYPrivate key content or file pathRequired for JWKS Issuer
APP_ENV_JWKS_PUBLIC_KEYPublic key content or file pathRequired for JWKS Issuer
APP_ENV_JWKS_KIDKey ID for JWKS endpointRequired for JWKS Issuer

Auth Modes

ModeBehavior
'any'First successful strategy wins (fallback mode)
'all'All strategies must pass (MFA mode)

Token Types

ConstantValueDescription
AuthenticationTokenTypes.TYPE_AUTHORIZATION_CODE'000_AUTHORIZATION_CODE'Authorization code grant type
AuthenticationTokenTypes.TYPE_ACCESS_TOKEN'100_ACCESS_TOKEN'Access token type
AuthenticationTokenTypes.TYPE_REFRESH_TOKEN'200_REFRESH_TOKEN'Refresh token type

Authentication Constants

ConstantValueDescription
Authentication.AUTHENTICATION_STRATEGY'authentication.strategy'Namespace prefix for strategy binding keys
Authentication.STRATEGY_JWT'jwt'JWT strategy name
Authentication.STRATEGY_BASIC'basic'Basic strategy name
Authentication.TYPE_BEARER'Bearer'Bearer token type prefix
Authentication.TYPE_BASIC'Basic'Basic token type prefix
Authentication.SKIP_AUTHENTICATION'authentication.skip'Context key to dynamically skip auth
Authentication.CURRENT_USER'auth.current.user'Context key for the authenticated user payload
Authentication.AUDIT_USER_ID'audit.user.id'Context key for the authenticated user ID

JWKS Constants

ClassConstantValueDescription
JOSEStandardsJWS'JWS'Symmetric JWT standard
JOSEStandardsJWKS'JWKS'Asymmetric JWT standard
JWKSModesISSUER'issuer'Issuer mode (sign + verify + serve JWKS)
JWKSModesVERIFIER'verifier'Verifier mode (verify-only via remote JWKS)
JWKSKeyDriversTEXT'text'Key provided as inline text
JWKSKeyDriversFILE'file'Key loaded from file path
JWKSKeyFormatsPEM'pem'PEM-encoded key format
JWKSKeyFormatsJWK'jwk'JSON Web Key format

Each constants class also provides:

  • SCHEME_SET: Set<string> — set of all valid values
  • isValid(input: string): boolean — check if a value is recognized

Import Paths

typescript
import {
  // Component + Registry
  AuthenticateComponent,
  AuthenticateBindingKeys,
  Authentication,
  AuthenticationFieldCodecs,
  AuthenticationModes,
  AuthenticationTokenTypes,
  AuthenticationStrategyRegistry,

  // JOSE Standards + Constants
  JOSEStandards,
  JWKSModes,
  JWKSKeyDrivers,
  JWKSKeyFormats,

  // Strategies
  JWSAuthenticationStrategy,
  JWKSIssuerAuthenticationStrategy,
  JWKSVerifierAuthenticationStrategy,
  BasicAuthenticationStrategy,

  // Services
  AbstractBearerTokenService,
  JWSTokenService,
  JWKSIssuerTokenService,
  JWKSVerifierTokenService,
  BasicTokenService,

  // Controllers
  defineAuthController,
  JWKSController,
  authenticate,
} from '@venizia/ignis';

import type {
  // Option types
  TAuthenticationRestOptions,
  TJWTTokenServiceOptions,
  IJWSTokenServiceOptions,
  IJWKSIssuerOptions,
  IJWKSVerifierOptions,
  TJWKSTokenServiceOptions,
  TBasicTokenServiceOptions,
  IAuthenticateOptions,

  // User + payload types
  IAuthUser,
  IJWTTokenPayload,
  IPayloadFieldCodec,
  IAuthService,
  IAuthenticationStrategy,

  // Controller types
  TDefineAuthControllerOpts,

  // Utility types
  TAuthStrategy,
  TAuthMode,
  TGetTokenExpiresFn,
  TJWKSAlgorithm,
  TJWKSKeyDriver,
  TJWKSKeyFormat,
  TJOSEStandard,
  TJWKSMode,
} from '@venizia/ignis';

Entity Column Helper Imports

typescript
import {
  extraUserColumns,
  extraRoleColumns,
  extraPermissionColumns,
  extraPolicyDefinitionColumns,
} from '@venizia/ignis';

import type {
  TPermissionOptions,
  TPermissionCommonColumns,
  TPolicyDefinitionOptions,
  TPolicyDefinitionCommonColumns,
} from '@venizia/ignis';

Status and Type Imports

typescript
import {
  UserStatuses,
  UserTypes,
  RoleStatuses,
} from '@venizia/ignis';

Component Binding Lifecycle

Setup

Step 1: Bind Configuration

Bind JWT options using the discriminated union TJWTTokenServiceOptions, which requires a standard field to select the JOSE standard.

JWS (Symmetric JWT) Setup

typescript
import {
  AuthenticateBindingKeys,
  JOSEStandards,
  TJWTTokenServiceOptions,
} from '@venizia/ignis';

this.bind<TJWTTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS }).toValue({
  standard: JOSEStandards.JWS,
  options: {
    jwtSecret: process.env.APP_ENV_JWT_SECRET,
    applicationSecret: process.env.APP_ENV_APPLICATION_SECRET, // Optional — enables AES payload encryption
    getTokenExpiresFn: () => Number(process.env.APP_ENV_JWT_EXPIRES_IN || 86400),
  },
});

Example .env file (JWS):

APP_ENV_JWT_SECRET=your-strong-jwt-secret
APP_ENV_APPLICATION_SECRET=your-strong-application-secret
APP_ENV_JWT_EXPIRES_IN=86400

NOTE

applicationSecret is optional. When provided, all custom JWT claim keys and values are AES-encrypted. When omitted, payloads are stored in plaintext (standard JWT behavior).

JWKS Issuer (Asymmetric JWT) Setup

typescript
import {
  AuthenticateBindingKeys,
  JOSEStandards,
  JWKSModes,
  JWKSKeyDrivers,
  JWKSKeyFormats,
  TJWTTokenServiceOptions,
} from '@venizia/ignis';

this.bind<TJWTTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS }).toValue({
  standard: JOSEStandards.JWKS,
  options: {
    mode: JWKSModes.ISSUER,
    algorithm: 'ES256',
    keys: {
      driver: JWKSKeyDrivers.FILE,     // or JWKSKeyDrivers.TEXT
      format: JWKSKeyFormats.PEM,       // or JWKSKeyFormats.JWK
      private: './keys/private.pem',
      public: './keys/public.pem',
    },
    kid: 'my-key-id-1',
    getTokenExpiresFn: () => Number(process.env.APP_ENV_JWT_EXPIRES_IN || 86400),
    // Optional AES payload encryption
    aesAlgorithm: 'aes-256-cbc',
    applicationSecret: process.env.APP_ENV_APPLICATION_SECRET,
  },
});

Example .env file (JWKS Issuer):

APP_ENV_JWKS_ALGORITHM=ES256
APP_ENV_JWKS_KEY_DRIVER=file
APP_ENV_JWKS_KEY_FORMAT=pem
APP_ENV_JWKS_PRIVATE_KEY=./keys/private.pem
APP_ENV_JWKS_PUBLIC_KEY=./keys/public.pem
APP_ENV_JWKS_KID=my-key-id-1
APP_ENV_JWT_EXPIRES_IN=86400
APP_ENV_APPLICATION_SECRET=your-strong-application-secret

JWKS Verifier (Remote Verification) Setup

typescript
import {
  AuthenticateBindingKeys,
  JOSEStandards,
  JWKSModes,
  TJWTTokenServiceOptions,
} from '@venizia/ignis';

this.bind<TJWTTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS }).toValue({
  standard: JOSEStandards.JWKS,
  options: {
    mode: JWKSModes.VERIFIER,
    jwksUrl: 'https://auth-service.example.com/certs',
    cacheTtlMs: 43_200_000,  // Cache JWKS for 12 hours (default)
    cooldownMs: 30_000,       // Wait 30s between JWKS refreshes (default)
    // Optional AES payload decryption (must match issuer's applicationSecret)
    aesAlgorithm: 'aes-256-cbc',
    applicationSecret: process.env.APP_ENV_APPLICATION_SECRET,
  },
});

Basic Auth Only (Alternative Setup)

typescript
import {
  AuthenticateBindingKeys,
  TBasicTokenServiceOptions,
} from '@venizia/ignis';

this.bind<TBasicTokenServiceOptions>({ key: AuthenticateBindingKeys.BASIC_OPTIONS }).toValue({
  verifyCredentials: async (opts) => {
    const { credentials, context } = opts;
    const user = await userRepo.findByUsername(credentials.username);
    if (user && await bcrypt.compare(credentials.password, user.passwordHash)) {
      return { userId: user.id, roles: user.roles };
    }
    return null;
  },
});

Combined JWKS + Basic with Auth Controller (Full Setup)

typescript
import {
  AuthenticateBindingKeys,
  JOSEStandards,
  JWKSModes,
  JWKSKeyDrivers,
  JWKSKeyFormats,
  TJWTTokenServiceOptions,
  TBasicTokenServiceOptions,
  TAuthenticationRestOptions,
  BindingKeys,
  BindingNamespaces,
} from '@venizia/ignis';

// Bind REST options (enables auth controller)
this.bind<TAuthenticationRestOptions>({ key: AuthenticateBindingKeys.REST_OPTIONS }).toValue({
  useAuthController: true,
  controllerOpts: {
    restPath: '/auth',
    serviceKey: BindingKeys.build({
      namespace: BindingNamespaces.SERVICE,
      key: AuthenticationService.name,
    }),
    payload: {
      signIn: {
        request: { schema: SignInRequestSchema },
        response: { schema: SignInResponseSchema },
      },
      signUp: {
        request: { schema: SignUpRequestSchema },
        response: { schema: SignUpResponseSchema },
      },
      changePassword: {
        request: { schema: ChangePasswordRequestSchema },
        response: { schema: ChangePasswordResponseSchema },
      },
    },
  },
});

// Bind JWT options (JWKS issuer mode)
this.bind<TJWTTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS }).toValue({
  standard: JOSEStandards.JWKS,
  options: {
    mode: JWKSModes.ISSUER,
    algorithm: 'ES256',
    keys: {
      driver: JWKSKeyDrivers.FILE,
      format: JWKSKeyFormats.PEM,
      private: './keys/private.pem',
      public: './keys/public.pem',
    },
    kid: 'my-key-id-1',
    getTokenExpiresFn: () => Number(process.env.APP_ENV_JWT_EXPIRES_IN || 86400),
  },
});

// Bind Basic auth options
this.bind<TBasicTokenServiceOptions>({ key: AuthenticateBindingKeys.BASIC_OPTIONS }).toValue({
  verifyCredentials: async (opts) => {
    const authenticateService = this.get<AuthenticationService>({
      key: BindingKeys.build({
        namespace: BindingNamespaces.SERVICE,
        key: AuthenticationService.name,
      }),
    });
    return authenticateService.signIn(opts.context, {
      identifier: { scheme: 'username', value: opts.credentials.username },
      credential: { scheme: 'basic', value: opts.credentials.password },
    });
  },
});

Step 2: Register Component and Strategies

typescript
import {
  AuthenticateComponent,
  Authentication,
  AuthenticationStrategyRegistry,
  JWKSIssuerAuthenticationStrategy,
  BasicAuthenticationStrategy,
  BaseApplication,
  ValueOrPromise,
} from '@venizia/ignis';

export class Application extends BaseApplication {
  preConfigure(): ValueOrPromise<void> {
    // Register your auth service (if using auth controller)
    this.service(AuthenticationService);

    // Step 1 bindings here...

    // Register component
    this.component(AuthenticateComponent);

    // Register strategies manually AFTER the component
    AuthenticationStrategyRegistry.getInstance().register({
      container: this,
      strategies: [
        { name: Authentication.STRATEGY_JWT, strategy: JWKSIssuerAuthenticationStrategy },
        { name: Authentication.STRATEGY_BASIC, strategy: BasicAuthenticationStrategy },
      ],
    });
  }
}

IMPORTANT

Strategies are NOT auto-registered by AuthenticateComponent. You must manually register them after calling this.component(AuthenticateComponent). This gives you full control over which strategies are available.

NOTE

Choose the strategy class matching your JOSE standard:

  • JWS: JWSAuthenticationStrategy
  • JWKS Issuer: JWKSIssuerAuthenticationStrategy
  • JWKS Verifier: JWKSVerifierAuthenticationStrategy

Configuration

TJWTTokenServiceOptions (Discriminated Union)

The top-level JWT options use a discriminated union on the standard field:

typescript
type TJWTTokenServiceOptions =
  | { standard: typeof JOSEStandards.JWS; options: IJWSTokenServiceOptions }
  | { standard: typeof JOSEStandards.JWKS; options: TJWKSTokenServiceOptions };

This enables clean TypeScript narrowing — once you set standard: JOSEStandards.JWS, the options field is typed as IJWSTokenServiceOptions; with standard: JOSEStandards.JWKS, it becomes TJWKSTokenServiceOptions.

JWS Options (IJWSTokenServiceOptions)

OptionTypeDefaultRequiredDescription
jwtSecretstring--YesSecret for signing and verifying JWT signature
getTokenExpiresFnTGetTokenExpiresFn--YesFunction returning token expiration in seconds
applicationSecretstring--NoSecret for AES-encrypting JWT payload fields
aesAlgorithmAESAlgorithmType'aes-256-cbc'NoAES algorithm for payload encryption
headerAlgorithmstring'HS256'NoJWT signing algorithm
fieldCodecsIPayloadFieldCodec[][]NoCustom field codecs for payload serialization
typescript
interface IJWSTokenServiceOptions {
  headerAlgorithm?: string;
  jwtSecret: string;
  getTokenExpiresFn: TGetTokenExpiresFn;
  aesAlgorithm?: AESAlgorithmType;
  applicationSecret?: string;
  fieldCodecs?: IPayloadFieldCodec[];
}

WARNING

jwtSecret is mandatory. The component will throw an error if it is missing or set to 'unknown_secret'. The error message from defineJWSAuth includes the actual provided secret value in the error output, so ensure these errors are never exposed to end users.

NOTE

applicationSecret is optional. When provided, custom JWT payload fields are AES-encrypted (keys and values). When omitted, the JWT payload is stored in standard plaintext. Standard JWT fields (iss, sub, aud, jti, nbf, exp, iat) are never encrypted.

JWKS Issuer Options (IJWKSIssuerOptions)

OptionTypeDefaultRequiredDescription
modetypeof JWKSModes.ISSUER--YesMust be 'issuer'
algorithmTJWKSAlgorithm--YesSigning algorithm: 'ES256', 'RS256', or 'EdDSA'
keys.driverTJWKSKeyDriver--YesKey source: 'text' (inline) or 'file' (file path)
keys.formatTJWKSKeyFormat--YesKey format: 'pem' or 'jwk'
keys.privatestring--YesPrivate key content (text) or file path (file)
keys.publicstring--YesPublic key content (text) or file path (file)
kidstring--YesKey ID exposed in the JWKS endpoint
getTokenExpiresFnTGetTokenExpiresFn--YesFunction returning token expiration in seconds
rest{ path: string }{ path: '/certs' }NoCustom path for the JWKS endpoint
aesAlgorithmAESAlgorithmType'aes-256-cbc'NoAES algorithm for payload encryption
applicationSecretstring--NoSecret for AES-encrypting JWT payload fields
fieldCodecsIPayloadFieldCodec[][]NoCustom field codecs for payload serialization
typescript
interface IJWKSIssuerOptions {
  mode: typeof JWKSModes.ISSUER;
  algorithm: TJWKSAlgorithm;
  rest?: { path: string };
  keys: {
    driver: TJWKSKeyDriver;
    format: TJWKSKeyFormat;
    private: string;
    public: string;
  };
  kid: string;
  getTokenExpiresFn: TGetTokenExpiresFn;
  aesAlgorithm?: AESAlgorithmType;
  applicationSecret?: string;
  fieldCodecs?: IPayloadFieldCodec[];
}

JWKS Verifier Options (IJWKSVerifierOptions)

OptionTypeDefaultRequiredDescription
modetypeof JWKSModes.VERIFIER--YesMust be 'verifier'
jwksUrlstring--YesURL of the remote JWKS endpoint
cacheTtlMsnumber43_200_000 (12h)NoHow long to cache the JWKS response
cooldownMsnumber30_000 (30s)NoMinimum time between JWKS refreshes
aesAlgorithmAESAlgorithmType'aes-256-cbc'NoAES algorithm for payload decryption
applicationSecretstring--NoSecret for AES-decrypting JWT payload fields
fieldCodecsIPayloadFieldCodec[][]NoCustom field codecs for payload deserialization
typescript
interface IJWKSVerifierOptions {
  mode: typeof JWKSModes.VERIFIER;
  jwksUrl: string;
  cacheTtlMs?: number;
  cooldownMs?: number;
  aesAlgorithm?: AESAlgorithmType;
  applicationSecret?: string;
  fieldCodecs?: IPayloadFieldCodec[];
}

IMPORTANT

In verifier mode, the applicationSecret must match the issuer's secret exactly. If the issuer encrypts payloads with AES, the verifier must use the same applicationSecret to decrypt them.

JWKS Token Service Options (Union)

typescript
type TJWKSTokenServiceOptions = IJWKSIssuerOptions | IJWKSVerifierOptions;

This union is discriminated on the mode field ('issuer' vs 'verifier').

Basic Auth Options

OptionTypeDefaultDescription
verifyCredentials(opts: { credentials, context }) => Promise<IAuthUser | null>--Callback to verify Basic auth credentials

The verifyCredentials function receives an options object:

typescript
type TBasicAuthVerifyFn<E extends Env = Env> = (opts: {
  credentials: { username: string; password: string };
  context: TContext<E, string>;
}) => Promise<IAuthUser | null>;

TBasicTokenServiceOptions -- Full Interface

typescript
type TBasicTokenServiceOptions<E extends Env = Env> = {
  verifyCredentials: (opts: {
    credentials: { username: string; password: string };
    context: TContext<E, string>;
  }) => Promise<IAuthUser | null>;
};

REST Options

OptionTypeDefaultDescription
useAuthControllerbooleanfalseEnable/disable built-in auth controller
controllerOptsTDefineAuthControllerOpts--Configuration for built-in auth controller (required when useAuthController is true)

TAuthenticationRestOptions is a discriminated union type:

typescript
type TAuthenticationRestOptions = {} & (
  | { useAuthController?: false | undefined }
  | {
      useAuthController: true;
      controllerOpts: TDefineAuthControllerOpts;
    }
);

IMPORTANT

When useAuthController is true, the controllerOpts field becomes required. The discriminated union enforces this at the type level -- you cannot set useAuthController: true without providing controllerOpts.

Controller Options

OptionTypeDefaultDescription
restPathstring'/auth'Base path for auth endpoints
serviceKeystring--DI key for the auth service (required)
requireAuthenticatedSignUpbooleanfalseWhether sign-up requires JWT authentication
payloadobject{}Custom Zod schemas for request/response payloads

TDefineAuthControllerOpts -- Full Interface

typescript
type TDefineAuthControllerOpts = {
  restPath?: string;
  serviceKey: string;
  requireAuthenticatedSignUp?: boolean;
  payload?: {
    signIn?: {
      request: { schema: TAnyObjectSchema };
      response: { schema: TAnyObjectSchema };
    };
    signUp?: {
      request: { schema: TAnyObjectSchema };
      response: { schema: TAnyObjectSchema };
    };
    changePassword?: {
      request: { schema?: TAnyObjectSchema };
      response: { schema: TAnyObjectSchema };
    };
  };
};

Route Configuration Options

Per-route authentication is configured via the authenticate field on route configs, using TRouteAuthenticateConfig:

typescript
type TRouteAuthenticateConfig =
  | { skip: true }
  | { skip?: false; strategies?: TAuthStrategy[]; mode?: TAuthMode };
OptionTypeDefaultDescription
authenticate.strategiesTAuthStrategy[]--Array of strategy names (e.g., ['jwt'], ['jwt', 'basic'])
authenticate.mode'any' | 'all''any'How to handle multiple strategies
authenticate.skiptrue--Skip authentication for this route

Example route config:

typescript
const SECURE_ROUTE = {
  path: '/data',
  method: HTTP.Methods.GET,
  authenticate: { strategies: [Authentication.STRATEGY_JWT] },
  responses: jsonResponse({ description: 'Protected', schema: z.object({ data: z.any() }) }),
} as const;

IAuthUser Interface

The base authenticated user type returned by strategies and available on the context:

typescript
interface IAuthUser {
  userId: IdType;
  [extra: string | symbol]: any;
}

TIP

IAuthUser is intentionally minimal. Your IAuthService implementation can extend the user payload with additional fields (roles, email, provider, etc.) -- these extra fields will be preserved through JWT token generation and available after authentication via Authentication.CURRENT_USER.

SignInRequestSchema Field Constraints

The built-in SignInRequestSchema enforces the following validation constraints on sign-in request payloads:

FieldTypeConstraints
identifier.schemestringNon-empty, min 4 chars (required)
identifier.valuestringNon-empty, min 8 chars (required)
credential.schemestringNon-empty (required)
credential.valuestringNon-empty, min 8 chars (required)
clientIdstringOptional

SignUpRequestSchema Field Constraints

The built-in SignUpRequestSchema uses a flat structure (not nested like SignInRequestSchema):

FieldTypeConstraints
usernamestringNon-empty, min 8 chars (required)
credentialstringNon-empty, min 8 chars (required)

ChangePasswordRequestSchema Field Constraints

The built-in ChangePasswordRequestSchema uses scheme-based credential naming:

FieldTypeConstraints
schemestringRequired
oldCredentialstringNon-empty, min 8 chars (required)
newCredentialstringNon-empty, min 8 chars (required)
userIdstring | numberRequired

IAuthService -- Full Interface

typescript
interface IAuthService<
  E extends Env = Env,
  SIRQ extends TSignInRequest = TSignInRequest,
  SIRS = AnyObject,
  SURQ extends TSignUpRequest = TSignUpRequest,
  SURS = AnyObject,
  CPRQ extends TChangePasswordRequest = TChangePasswordRequest,
  CPRS = AnyObject,
  UIRQ = AnyObject,
  UIRS = AnyObject,
> {
  signIn(context: TContext<E>, opts: SIRQ): Promise<SIRS>;
  signUp(context: TContext<E>, opts: SURQ): Promise<SURS>;
  changePassword(context: TContext<E>, opts: CPRQ): Promise<CPRS>;
  getUserInformation?(context: TContext<E>, opts: UIRQ): Promise<UIRS>;
}

NOTE

IAuthService is generic on the Hono Env type as well as all request/response types. The getUserInformation method is optional.

IJWTTokenPayload -- Full Interface

typescript
interface IJWTTokenPayload extends JWTPayload, IAuthUser {
  userId: IdType;
  roles: { id: IdType; identifier: string; priority: number }[];
  clientId?: string;
  provider?: string;
  email?: string;
  name?: string;
  [extra: string | symbol]: any;
}

Binding Keys

KeyConstantTypeRequiredDefault
@app/authenticate/rest-optionsAuthenticateBindingKeys.REST_OPTIONSTAuthenticationRestOptionsNo{ useAuthController: false }
@app/authenticate/jwt-optionsAuthenticateBindingKeys.JWT_OPTIONSTJWTTokenServiceOptionsConditional--
@app/authenticate/jwks-optionsAuthenticateBindingKeys.JWKS_OPTIONSIJWKSIssuerOptions | IJWKSVerifierOptionsInternalBound by the component
@app/authenticate/basic-optionsAuthenticateBindingKeys.BASIC_OPTIONSTBasicTokenServiceOptionsConditional--

IMPORTANT

At least one of JWT_OPTIONS or BASIC_OPTIONS must be bound. If neither is configured, the component will throw an error during binding().

NOTE

JWKS_OPTIONS is bound internally by the component when standard: JOSEStandards.JWKS is configured. You do not need to bind it manually. The component extracts the JWKS options from the discriminated union and re-binds them to JWKS_OPTIONS so that the JWKS services can resolve them via @inject.

Context Variables

These values are set on the Hono Context during authentication and can be accessed via context.get():

KeyConstantTypeDescription
auth.current.userAuthentication.CURRENT_USERIAuthUserAuthenticated user payload
audit.user.idAuthentication.AUDIT_USER_IDIdTypeAuthenticated user's ID
authentication.skipAuthentication.SKIP_AUTHENTICATIONbooleanDynamically skip auth

Strategy Constants

ConstantValueDescription
Authentication.STRATEGY_JWT'jwt'JWT strategy name
Authentication.STRATEGY_BASIC'basic'Basic strategy name
Authentication.TYPE_BEARER'Bearer'Bearer token type
Authentication.TYPE_BASIC'Basic'Basic token type

AuthenticateStrategy Class

Utility class for validating strategy names:

typescript
class AuthenticateStrategy {
  static readonly BASIC = 'basic';
  static readonly JWT = 'jwt';
  static readonly SCHEME_SET: Set<string>;
  static isValid(input: string): boolean;
}
type TAuthStrategy = TConstValue<typeof AuthenticateStrategy>;
MemberTypeDescription
BASICstringConstant for basic strategy name
JWTstringConstant for JWT strategy name
SCHEME_SETSet<string>Set containing all valid strategy names
isValid(input)(input: string) => booleanReturns true if the input is a recognized strategy name

AuthenticationModes Class

Utility class for validating authentication modes:

typescript
class AuthenticationModes {
  static readonly ANY = 'any';
  static readonly ALL = 'all';
}
type TAuthMode = TConstValue<typeof AuthenticationModes>;
MemberTypeDescription
ANYstringFirst successful strategy wins (fallback)
ALLstringAll strategies must pass (MFA)

See Also