# @axa-fr/vanilla-oidc 中文文档

规范地址：https://npmcn.com/package/%40axa-fr/vanilla-oidc/

版本：6\.25\.6
npm 元数据更新时间：2025-12-08T13:49:48.972Z
中文译文更新时间：2026-11-07T23:45:08.563Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40axa-fr/vanilla-oidc
原文对照：https://npmcn.com/package/%40axa-fr/vanilla-oidc/?lang=original
项目主页：https://github.com/AxaGuilDEv/react-oidc#readme
源码仓库：https://github.com/AxaGuilDEv/react-oidc

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：274 kB，82 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2019-03-08T08:43:19.873Z
- 最新版本发布：2023-07-24T12:33:55.454Z
- 近 30 天下载量：1989（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：317（近 12 个月 0 个）

## 中文简介

OpenID Connect & OAuth 认证只使用本地的javascript,兼容角,反应,vue,svelte,下等.

## 安装

```sh
npm install @axa-fr/vanilla-oidc
```

也可以使用：`pnpm add @axa-fr/vanilla-oidc`、`yarn add @axa-fr/vanilla-oidc`、`bun add @axa-fr/vanilla-oidc`

## README

# @axa-fr/vanilla-oidc (英语)

[![Continuous Integration](https://github.com/AxaGuilDEv/react-oidc/actions/workflows/npm-publish.yml/badge.svg)](https://github.com/AxaGuilDEv/react-oidc/actions/workflows/npm-publish.yml) [![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=AxaGuilDEv_react-oidc&metric=alert_status)](https://sonarcloud.io/dashboard?id=AxaGuilDEv_react-oidc) [![Reliability](https://sonarcloud.io/api/project_badges/measure?project=AxaGuilDEv_react-oidc&metric=reliability_rating)](https://sonarcloud.io/component_measures?id=AxaGuilDEv_react-oidc&metric=reliability_rating) [![Security](https://sonarcloud.io/api/project_badges/measure?project=AxaGuilDEv_react-oidc&metric=security_rating)](https://sonarcloud.io/component_measures?id=AxaGuilDEv_react-oidc&metric=security_rating) [![Code Corevage](https://sonarcloud.io/api/project_badges/measure?project=AxaGuilDEv_react-oidc&metric=coverage)](https://sonarcloud.io/component_measures?id=AxaGuilDEv_react-oidc&metric=Coverage) [![Twitter](https://img.shields.io/twitter/follow/GuildDEvOpen?style=social)](https://twitter.com/intent/follow?screen_name=GuildDEvOpen)

试试演示 [https://icy-glacier-004ab4303. azurestaticapps.net/ 互联网档案馆的存檔,存档日期2013-12-22](https://icy-glacier-004ab4303.2.azurestaticapps.net/)

-   [关于](https://npmcn.com/package/%40axa-fr/vanilla-oidc/#readme-about)
-   [开始](https://npmcn.com/package/%40axa-fr/vanilla-oidc/#readme-getting-started)
-   [运行演示](https://npmcn.com/package/%40axa-fr/vanilla-oidc/#readme-run-the-demo)
-   [如何运作](https://npmcn.com/package/%40axa-fr/vanilla-oidc/#readme-how-it-works)
-   [散列路线](https://npmcn.com/package/%40axa-fr/vanilla-oidc/#readme-Hash-route)
-   [服务工人支助](https://npmcn.com/package/%40axa-fr/vanilla-oidc/#readme-service-worker-support)

## 关于

@axa-fr/vanilla-oidc是一个纯OIDC客户端库,对任何框架都是不可知论的. 它被@axa-fr/react-oidc使用,可以被任何框架使用.

它是现有类离子客户端库的真正替代品.

-   **安全** 数字 :
    -   由于使用Service Worker,您的令牌(refresh token and access token)无法访问JavaScript客户端代码(大保护以防范XSRF攻击)
    -   OIDC 仅使用 PKCE 客户端代码证书赠款
-   **轻巧**
-   **简单** 数字 :
    -   刷新 token 和 access token 在背景中自动刷新
    -   您无需在每次获取时输入访问权限 ken,只需配置 `OidcTrustedDomains.js` 文件
-   **没有饼干问题** : 您可以禁用无声符号( 内部使用 iframe) 。 您的 OIDC 服务器应该位于您网站的同域, 以便通过 IFRAME 从您的网站发送 OIDC 服务器 cookie, 否则您可能会遇到 CoOKIES 问题 .
-   **多重认证** 数字 :
    -   您可以多次认证给同一提供商, 范围不同( 例如, 您可以获得一个新的“ 支付” 支付范围 )
    -   您可以在同一 SPA (单一页面应用程序) 网站上认证多个不同的供应商
-   **弹性** 数字 :
    -   与 Service Worker 合作( 更安全) , 不为旧浏览器工作( 不安全)

![](https://github.com/AxaGuilDEv/react-oidc/blob/master/docs/img/schema_pcke_client_side_with_service_worker.png?raw=true)

服务员抓住了 **访问( t)** 财务报告和审定财务报表 **刷新( tk)** 客户永远无法访问.

### 开始

```sh
npm install @axa-fr/vanilla-oidc --save

# If you have a "public" folder, the 2 files will be created :
# ./public/OidcServiceWorker.js <-- will be updated at each "npm install"
# ./public/OidcTrustedDomains.js <-- won't be updated if already exist
```

如果您需要非常安全的模式, 刷新 token 和访问 token 将会隐藏在服务员的后方, 以复制请求 . 你唯一应该编辑的文件是"OidcTrustedDomains.js".

```javascript
// OidcTrustedDomains.js

// Add bellow trusted domains, access tokens will automatically injected to be send to
// trusted domain can also be a path like https://www.myapi.com/users,
// then all subroute like https://www.myapi.com/useers/1 will be authorized to send access_token to.

// Domains used by OIDC server must be also declared here
const trustedDomains = {
  default: ["https://demo.duendesoftware.com", "https://www.myapi.com/users"],
};
```

演示的代码 :

```js
import { VanillaOidc } from '@axa-fr/vanilla-oidc'

export const configuration = {
    client_id: 'interactive.public.short',
    redirect_uri: window.location.origin + '/#/authentication/callback',
    silent_redirect_uri: window.location.origin + '/#/authentication/silent-callback',
    scope: 'openid profile email api offline_access',
    authority: 'https://demo.duendesoftware.com',
    service_worker_relative_url:'/OidcServiceWorker.js',
    service_worker_only: false,
};

const href = window.location.href;
const vanillaOidc = VanillaOidc.getOrCreate(() => fetch)(configuration);

console.log(href);

vanillaOidc.tryKeepExistingSessionAsync().then(() => {
    if(href.includes(configuration.redirect_uri)){
        vanillaOidc.loginCallbackAsync().then(()=>{
            window.location.href = "/";
        });
        document.body.innerHTML = `<div>
            <h1>@axa-fr/vanilla-oidc demo</h1>
            <h2>Loading</h2>
        </div>`;
        return
    }

    let tokens = vanillaOidc.tokens;

    if(tokens){

        // @ts-ignore
        window.logout = () =>  vanillaOidc.logoutAsync();
        document.body.innerHTML = `<div>
            <h1>@axa-fr/vanilla-oidc demo</h1>
            <button onclick="window.logout()">Logout</button>
            <h2>Authenticated</h2>
            <pre>${JSON.stringify(tokens,null,'\t')}</pre>
        </div>`
        
    }
    else {
        // @ts-ignore
        window.login= () =>  vanillaOidc.loginAsync("/");
        document.body.innerHTML = `<div>
            <h1>@axa-fr/vanilla-oidc demo</h1>
            <button onclick="window.login()">Login</button>
        </div>`
    }
})


```

## 配置

```javascript
const configuration: {
    client_id: PropTypes.string.isRequired, // oidc client id
    redirect_uri: PropTypes.string.isRequired, // oidc redirect url
    silent_redirect_uri: PropTypes.string, // Optional activate silent-signin that use cookies between OIDC server and client javascript to restore sessions
    silent_login_uri: PropTypes.string, // Optional, route that trigger the signin
    silent_login_timeout: PropTypes.number, // Optional default is 12000 milliseconds
    scope: PropTypes.string.isRequired, // oidc scope (you need to set "offline_access")
    authority: PropTypes.string.isRequired,
    storage: Storage, // Default sessionStorage, you can set localStorage but it is less secure to XSS attacks
    authority_configuration: PropTypes.shape({
      // Optional for providers that does not implement OIDC server auto discovery via a .wellknowurl
      authorization_endpoint: PropTypes.string,
      token_endpoint: PropTypes.string,
      userinfo_endpoint: PropTypes.string,
      end_session_endpoint: PropTypes.string,
      revocation_endpoint: PropTypes.string,
      check_session_iframe: PropTypes.string,
      issuer: PropTypes.string,
    }),
    refresh_time_before_tokens_expiration_in_second: PropTypes.number, // default is 120 seconds
    service_worker_relative_url: PropTypes.string,
    service_worker_only: PropTypes.boolean, // default false
    service_worker_convert_all_requests_to_cors: PropTypes.boolean, // force all requests that servie worker upgrades to have 'cors' mode. This allows setting authentication token on requests initialted by html parsing(e.g. img tags, download links etc).
    extras: StringMap | undefined, // ex: {'prompt': 'consent', 'access_type': 'offline'} list of key/value that are send to the oidc server (more info: https://github.com/openid/AppAuth-JS)
    token_request_extras: StringMap | undefined, // ex: {'prompt': 'consent', 'access_type': 'offline'} list of key/value that are send to the oidc server during token request (more info: https://github.com/openid/AppAuth-JS)
    withCustomHistory: PropTypes.function, // Override history modification, return instance with replaceState(url, stateHistory) implemented (like History.replaceState())
    authority_time_cache_wellknowurl_in_second: 60 * 60, // Time to cache in second of openid wellknowurl, default is 1 hour
    authority_timeout_wellknowurl_in_millisecond: 10000, // Timeout in millisecond of openid wellknowurl, default is 10 seconds, then error is throwed
    monitor_session: PropTypes.boolean, // Add OpenId monitor session, default is false (more information https://openid.net/specs/openid-connect-session-1_0.html), if you need to set it to true consider https://infi.nl/nieuws/spa-necromancy/
    onLogoutFromAnotherTab: Function, // Optional, can be set to override the default behavior, this function is triggered when user with the same subject is logged out from another tab when session_monitor is active
    onLogoutFromSameTab: Function, // Optional, can be set to override the default behavior, this function is triggered when user is logged out from same tab when session_monitor is active
    token_renew_mode: PropTypes.string, // Optional, update tokens base on the selected token(s) lifetime: "access_token_or_id_token_invalid" (default), "access_token_invalid" , "id_token_invalid"
    logout_tokens_to_invalidate : Array<string> // Optional tokens to invalidate during logout, default: ['access_token', 'refresh_token']
  };
```

## 运行演示

```sh
git clone https://github.com/AxaGuilDEv/react-oidc.git
cd react-oidc/packages/vanilla-demo
npm install
npm start
# then navigate to http://localhost:3000
```

## 如何运作

这个组件是一个纯梵文JS OIDC客户端库,对任何框架都是不可知的. 它是现有类离子客户端库的真正替代品.

更多关于OIDC的信息

-   [法语:Agamentez la security la security and la simplicé de votre Système d ' Information OpenID Connection 互联网档案馆的存檔,存档日期2013-12-20](https://medium.com/just-tech-it-now/augmentez-la-s%C3%A9curit%C3%A9-et-la-simplicit%C3%A9-de-votre-syst%C3%A8me-dinformation-avec-oauth-2-0-cf0732d71284)
-   [英语: 增加您的信息系统的安全性和简洁性, 并使用可打开的连接](https://medium.com/just-tech-it-now/increase-the-security-and-simplicity-of-your-information-system-with-openid-connect-fa8c26b99d6d)

## 散列路线

`vanilla-oidc` 还有散列路线.

```javascript
export const configurationIdentityServerWithHash = {
  client_id: "interactive.public.short",
  redirect_uri: window.location.origin + "#authentication-callback",
  silent_redirect_uri:
    window.location.origin + "#authentication-silent-callback",
  scope: "openid profile email api offline_access",
  authority: "https://demo.duendesoftware.com",
  refresh_time_before_tokens_expiration_in_second: 70,
  service_worker_relative_url: "/OidcServiceWorker.js",
  service_worker_only: false,
};
```

## 服务工人支助

-   Firefox:在Firefox上测试 98.0.2
-   Chrome/Edge:在上至90版本测试
-   歌剧:在上至80版本测试
-   Safari:在Safari/605.1.15上测试

## 常见问题

### @axa-fr/vanilla-oidc 是什么？

OpenID Connect & OAuth 认证只使用本地的javascript,兼容角,反应,vue,svelte,下等\.

### 如何安装 @axa-fr/vanilla-oidc？

在项目目录运行 npm install @axa-fr/vanilla-oidc，或使用 pnpm add / yarn add / bun add。

### @axa-fr/vanilla-oidc 支持 TypeScript 吗？

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

### @axa-fr/vanilla-oidc 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @axa-fr/vanilla-oidc 可以商用吗？

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

### @axa-fr/vanilla-oidc 的下载量有多少？

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

### @axa-fr/vanilla-oidc 还在维护吗？

最新版本 6\.25\.6 发布于 2023/07/24（3 年前）；至今共发布 317 个版本，其中过去 12 个月发布了 0 个；首次发布于 2019/03/08。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

