@defra/hapi-auth-oidc

中文文档
0.6.1发布于 2026/11/04OGL-UK-3.0ES Module构建来源已验证近 30 天下载 4593

A lightweight Node.js library for authentication using OIDC tokens and hapi server integration.

原始使用文档
文档目录13 节
  1. Features
  2. Installation
  3. Usage
  4. Importing from the library
  5. Registering the plugin
  6. Decorating requests
  7. Token refresh
  8. Configuration
  9. Plugin options
  10. Token Providers
  11. CognitoTokenProvider
  12. MockProvider
  13. Example Usage

Hapi Auth OIDC

A Hapi.js plugin providing OpenID Connect (OIDC) authentication with PKCE support. Supports federated Cognito tokens, mock tokens for testing, and automatic token validation and refresh. Designed for server-side Hapi applications.

Features

  • login redirect to OIDC provider with PKCE support
  • Auth callback handling with token validation
  • Automatic access token refresh with configurable early refresh window
  • Federated token support via Cognito Identity Pools
  • request decoration ensureValidToken, login and handle callbacks
  • Mock OIDC provider for development and testing environments
  • form_post and query auth callback support
  • Fully configurable cookie options

Installation

npm install @defra/hapi-auth-oidc

Usage

Importing from the library

All public functions, providers, and plugins are exported from the library entry point:

import {
  HapiAuthOidcPlugin,
  CognitoTokenProvider,
  MockProvider,
  preLogin,
  postLogin,
  ensureValidToken
} from '@defra/hapi-auth-oidc'

Alternatively, import the entire library as a namespace:

import * as OIDC from '@defra/hapi-auth-oidc'
const plugin = OIDC.HapiAuthOidcPlugin
const tokenProvider = new OIDC.CognitoTokenProvider({...})

Registering the plugin

import Hapi from '@hapi/hapi'
import { AuthOidcPlugin } from './auth-oidc.js'

const server = Hapi.server({ port: 3000 })

await server.register(AuthOidcPlugin)

Decorating requests

server.route({
  method: 'GET',
  path: '/protected',
  handler: async (request, h) => {
    const { token, refreshed } = await request.ensureValidToken(
      request.auth.credentials
    )
    return { token }
  }
})

Token refresh

Standalone usage:

import { ensureValidToken } from '@defra/hapi-auth-oidc'

const refreshedToken = await ensureValidToken(
  { accessToken, refreshToken },
  getOidcConfig,
  60000,
  oidcScope,
  logger
)

Configuration

Plugin options

  • oidc - OIDC configuration object:

    • clientId - OIDC client ID
    • discoveryUri - URL for OIDC discovery document
    • authProvider - Token provider (CognitoTokenProvider or MockProvider)
    • useHttp - Boolean flag to allow insecure HTTP requests for discovery (default: false)
    • loginCallbackUri - Redirect URI after OIDC login
    • scope - Space-separated string of scopes
    • externalBaseUrl - Base URL used to construct absolute callback URLs
    • defaultPostLoginUri - Redirect URI after login if not otherwise specified (default: '/')
    • earlyRefreshMs - Milliseconds before token expiry to refresh early (default: 60000)
  • cookieOptions - Cookie options for Iron encryption and security

    • password - Secret used for Iron encryption (required)
    • isSecure - Send cookie over HTTPS only (default: true)
    • encoding - 'none' | 'base64' | 'base64json' | 'iron' (default: 'iron')
    • path - Cookie path (default: '/')
    • isHttpOnly - Cookie inaccessible to client-side JS (default: true)
    • isSameSite - 'Strict' | 'Lax' | 'None' (default: 'Lax')
    • ttl - Time-to-live in milliseconds (optional)
    • domain - Cookie domain (optional)
    • ignoreErrors - Ignore encoding errors (default: true)
    • clearInvalid - Automatically clear invalid cookies (default: true)

Token Providers

CognitoTokenProvider

  • Federated token provider for AWS Cognito Identity Pools.
  • Automatically caches the token and refreshes it before expiry.
  • Supports optional early refresh via earlyRefreshMs.

MockProvider

  • Simple mock token provider for development/testing.
  • Returns a hardcoded token.

Example Usage

import { config } from '../../../config/config.js'
import {
  CognitoTokenProvider,
  HapiAuthOidcPlugin,
  MockProvider
} from '@defra/hapi-auth-oidc'

const authProvider = config.get('isProduction')
  ? new CognitoTokenProvider({
      poolId: config.get('azureFederatedCredentials.identityPoolId'),
      logins: { 'cdp-portal-frontend-aad-access': 'cdp-portal-frontend' }
    })
  : new MockProvider({})

const oidcCookieConfig = config.get('hapi-auth-oidc.cookie')

export const AuthOidcPlugin = {
  plugin: HapiAuthOidcPlugin,
  options: {
    oidc: {
      clientId: config.get('azureClientId'),
      discoveryUri: config.get('oidcWellKnownConfigurationUrl'),
      authProvider,
      useHttp: config.get('isProduction'),
      loginCallbackUri: config.get('appBaseUrl') + '/auth/callback',
      scope: `api://${config.get('azureClientId')}/cdp.user openid profile email offline_access user.read`,
      externalBaseUrl: config.get('appBaseUrl')
    },
    cookieOptions: {
      isSecure: oidcCookieConfig.isSecure,
      password: oidcCookieConfig.password
    }
  }
}

版本与发布记录

@defra/hapi-auth-oidc 共发布 13 个版本,首次发布于 2026/02/11;过去 12 个月发布了 13 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.6.1latest2026/11/048 天前
0.6.02026/10/051 个月前
0.5.62026/07/074 个月前
0.5.52026/06/294 个月前
0.5.42026/06/224 个月前
0.5.32026/06/224 个月前

关于 @defra/hapi-auth-oidc 的常见问题

@defra/hapi-auth-oidc 是什么?

A lightweight Node.js library for authentication using OIDC tokens and hapi server integration.

如何安装 @defra/hapi-auth-oidc?

在项目目录运行 npm install @defra/hapi-auth-oidc,或使用 pnpm add / yarn add / bun add。

@defra/hapi-auth-oidc 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/defra__hapi-auth-oidc 是否存在。

@defra/hapi-auth-oidc 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@defra/hapi-auth-oidc 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@defra/hapi-auth-oidc 可以商用吗?

@defra/hapi-auth-oidc 使用 OGL-UK-3.0 许可。声明的许可为 OGL-UK-3.0,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@defra/hapi-auth-oidc 的下载量有多少?

根据 npm 官方下载统计,@defra/hapi-auth-oidc 在 2026/10/12 – 2026/11/10 这 30 天内被下载 4,593 次,日均约 153 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@defra/hapi-auth-oidc 还在维护吗?

最新版本 0.6.1 发布于 2026/11/04(8 天前);至今共发布 13 个版本,其中过去 12 个月发布了 13 个;首次发布于 2026/02/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。