@batoanng/oidc

中文文档
3.1.0发布于 2026/05/01MITTypeScriptES Module零依赖近 30 天下载 1922

npm version install size

原始使用文档
文档目录12 节
  1. Features
  2. Installation
  3. Usage
  4. Auth Flow
  5. Props
  6. OidcAuthorisationProvider
  7. OidcAuthorisationCallback
  8. Integration Notes
  9. Default routes
  10. Axios behavior
  11. Related packages
  12. Development

@batoanng/oidc

npm version install size

@batoanng/oidc wraps react-oidc-context with router-aware callback routes, a shared authorisation context, post-login enrichment helpers, and ready-made authentication status screens for React single-page applications.

Features

  • Wraps react-oidc-context with login, logout, and expired-password routing.
  • Exposes a shared authorisation context through useOidcAuthorisationContext, useChallenge, and useChallengeResult.
  • Provides OidcAuthorisationCallback for post-login profile and privilege loading.
  • Can wire an axios client with Authorization headers and a single silent-refresh retry on 401.
  • Ships reset-password, error, and status screens built on @batoanng/mui-components.

Installation

pnpm add @batoanng/oidc

Peer dependencies include react, react-router-dom, react-oidc-context, oidc-client-ts, axios, @mui/material, @emotion/react, react-hook-form, react-use, and @batoanng/mui-components.

If you use the built-in screens from @batoanng/mui-components, install any additional peers required by that package as well.

Usage

Wrap the routed part of your app with OidcAuthorisationProvider. The provider must live inside a React Router <Router> because it injects callback routes with <Routes>.

import { OidcAuthorisationProvider } from '@batoanng/oidc';

export function AppShell() {
  return (
    <OidcAuthorisationProvider
      userManagerSettings={{
        authority: 'https://your-idp.example.com',
        client_id: 'web-app',
        redirect_uri: 'http://localhost:3000/oidc/callback',
        post_logout_redirect_uri: 'http://localhost:3000/oidc/logout',
      }}
    >
      <AppRoutes />
    </OidcAuthorisationProvider>
  );
}

After the login callback completes, load the user profile and privileges, then hand them to OidcAuthorisationCallback so the shared authorisation context is populated before your protected UI renders.

import axios from 'axios';
import {
  OidcAuthorisationCallback,
  useOidcAuthorisationContext,
  useEnsureOidcLoginToken,
} from '@batoanng/oidc';

const apiClient = axios.create({
  baseURL: '/api',
});

export function PostLoginGate() {
  const userInformation = {
    shortName: 'T. User',
    fullName: 'Test User',
    email: '[email protected]',
  };

  const privileges = {
    'activityLog.read': true,
  };

  return (
    <OidcAuthorisationCallback apiClient={apiClient} userInformation={userInformation} privileges={privileges}>
      <ProtectedApp />
    </OidcAuthorisationCallback>
  );
}

export function ProtectedPage() {
  useEnsureOidcLoginToken();
  const { isAuthenticated, onLogout, token } = useOidcAuthorisationContext();

  return (
    <section>
      <div>{isAuthenticated ? 'Signed in' : 'Signed out'}</div>
      <div>{token}</div>
      <button onClick={() => void onLogout()}>Logout</button>
    </section>
  );
}

Auth Flow

flowchart TD
  A["App Router"] --> B["OidcAuthorisationProvider"]
  B --> C["react-oidc-context AuthProvider"]
  B --> D["/oidc/callback -> OidcLoginCallback"]
  B --> E["/oidc/logout -> OidcLogoutCallback"]
  B --> F["* -> OidcAuthorisationContextProvider"]
  D --> G{"Expired password response?"}
  G -- "Yes" --> H["/expired -> OidcResetPasswordPage"]
  G -- "No" --> I["Navigate to postLoginUrl or /"]
  F --> J["AuthorisationContext"]
  J --> K["useOidcAuthorisationContext / useChallenge"]
  I --> L["Load user profile and privileges"]
  L --> M["OidcAuthorisationCallback"]
  M --> N["Update user information and privilege state"]
  M --> O["Optional axios header + 401 retry wiring"]
  N --> P["Protected application UI"]
  O --> P

Props

OidcAuthorisationProvider

PropTypeNotes
userManagerSettingsUserManagerSettingsPassed through to react-oidc-context's AuthProvider.
loginCallbackRelativeUrlstringOptional override for the login callback route. Defaults to the pathname from redirect_uri, or /oidc/callback.
logoutCallbackRelativeUrlstringOptional override for the logout callback route. Defaults to the pathname from post_logout_redirect_uri, or /oidc/logout.
onLoggingIn(options?: LoginOptions) => void | boolean | Promise<void | boolean>Return false to cancel a login attempt.
onLoggingOut() => void | boolean | Promise<void | boolean>Return false to cancel a logout attempt.
onPasswordReset(email: string) => void | boolean | Promise<void | boolean>Called when the expired-password flow submits or resends a reset email.

OidcAuthorisationCallback

PropTypeNotes
apiClientAxiosInstanceOptional axios instance that receives Authorization header updates and a single silent-refresh retry on 401.
userInformationUserInformation | stringProvide the loaded user profile, or a redirect URL string to navigate away after login.
privilegesUserPrivilegesThe resolved privilege map for the current user.
errorError | nullRenders the built-in login error state and lets the user log out.
authSchemestringAuthorization scheme used when populating the Authorization header. Defaults to Bearer.

Integration Notes

Default routes

RoutePurpose
/oidc/callbackHandles the OIDC login redirect.
/oidc/logoutHandles the OIDC logout redirect.
/expiredShows the password reset flow when the IdP reports an expired-password response.

Axios behavior

  • setBearerToken stores the current access token on the axios instance and keeps defaults.headers.common.Authorization in sync.
  • OidcAuthorisationCallback installs one response interceptor for the provided apiClient.
  • A 401 triggers one signinSilent() attempt. If a new token is returned, the failed request is retried once with a refreshed Authorization header.
  • @batoanng/mui-components supplies the status, notification, and form primitives used by the built-in screens.
  • @batoanng/utils is a related workspace utility package, but @batoanng/oidc now uses react-use directly for its local hook helpers.

Development

pnpm --dir packages/oidc lint
pnpm --dir packages/oidc type-check
pnpm --dir packages/oidc test
pnpm --dir packages/oidc build

Key files:

  • src/OidcAuthorisationProvider.tsx
  • src/OidcAuthorisationContextProvider.tsx
  • src/OidcAuthorisationCallback.tsx
  • src/hooks.ts
  • src/types.ts

版本与发布记录

@batoanng/oidc 共发布 34 个版本,首次发布于 2025/07/11;过去 12 个月发布了 22 个版本。

版本发布日期距今
3.1.0latest2026/05/016 个月前
3.0.52026/04/286 个月前
3.0.42026/04/077 个月前
3.0.32026/04/077 个月前
3.0.22026/04/067 个月前
3.0.12026/04/067 个月前

关于 @batoanng/oidc 的常见问题

如何安装 @batoanng/oidc?

在项目目录运行 npm install @batoanng/oidc,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@batoanng/mui-components(^3.6.0)、@emotion/react(^11.14.0)、@mui/material(9.0.0)、axios(1.15.2)、oidc-client-ts(^3.5.0)、react(^19.2.5)、react-hook-form(7.74.0)、react-oidc-context(^3.3.1)、react-router-dom(^7.14.2)、react-use(^17.4.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@batoanng/oidc 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@batoanng/oidc 支持 ESM 还是 CommonJS?

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

@batoanng/oidc 需要什么版本的 Node.js?

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

@batoanng/oidc 可以商用吗?

@batoanng/oidc 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@batoanng/oidc 的下载量有多少?

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

@batoanng/oidc 还在维护吗?

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