# @curity/oauth-assistant 中文文档

规范地址：https://npmcn.com/package/%40curity/oauth-assistant/

版本：2\.0\.0
npm 元数据更新时间：2026-04-20T15:58:44.395Z
中文译文更新时间：2026-11-11T05:00:37.558Z
软件包许可：UNLICENSED

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

原始 npm 页面：https://www.npmjs.com/package/%40curity/oauth-assistant
原文对照：https://npmcn.com/package/%40curity/oauth-assistant/?lang=original

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

- 包体积（解压后）：78.7 kB，6 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2020-07-06T10:44:32.300Z
- 最新版本发布：2026-04-20T15:58:44.179Z
- 近 30 天下载量：3191（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：28（近 12 个月 2 个）

## 中文简介

JS OAuth 助理律师

## 安装

```sh
npm install @curity/oauth-assistant
```

也可以使用：`pnpm add @curity/oauth-assistant`、`yarn add @curity/oauth-assistant`、`bun add @curity/oauth-assistant`

## README

# 隐私 OAuth 助理

## 添加到项目

使用 npm 添加到您的工程中

```
npm install @curity/oauth-assistant
```

线条

```
yarn add @curity/oauth-assistant
```

## 如何在您的项目中使用

### 初始化助理

要初始化助手, 您需要在设置对象中通过 .

以下是示例设置对象 .

```
const settings = {
    flow_type      : "code", // Possible values : (code, implicit, assisted_token)
    base_url       : "http://localhost:8443",
    client_id      : "test_client_id",
    issuer         : "https://localhost:8443/oauth/v2/oauth-anonymous",
    redirect_uri   : "http://localhost:8080/assisted.html", // Basic version of assisted.html is available in example/assisted.html but it can be customized as needed.
    for_origin     : "http://localhost:8080",
    iframe         : { // Optional: Passing in null would take default values
        targetElement: null, // targetElement querySelector , default: 'body'
        width   : null, // take default value : 400
        height  : null, // take default value : 700
        style   : null, // take default value
        backdrop: {
            visible      : true, // default is true
            style        : null, // take default value
            backdropClass: ""
        },
        extraAttributes: null, // extra attributes added to the iframe, i.e { "allow": "example.com" }
        closeButton: {
            visible: true, // default is true
            style  : null, // style for wrapper div of close button
            class  : "",
            button : null
        },
    },
    "popup": {
        "width" :  null,  // take default value : 400
        "height": null   // take default value : 600
    },
    allowed_origins: ["http://localhost:8443", "http://localhost:8080"], // default is [window.origin]
    disable_session_management: false, // Optional: if set to true, session management will be disabled
    check_session_iframe: null, // Optional url, if not provided then it will be resolved from metadata
    session_polling_interval: 5, // Optional: polling interval in seconds, default is 5
    check_session_iframe_events: { // Optional
            onStateChanging: () => {},
            onStateChanged: () => {},
            onLogout: () => {},
            onConsent: () => {},
            onError: () => {},
            onUnchanged: () => {},
    },
    allowed_jwt_algorithms: ['RS256'], // Optional: algorithms to trust for JWT validation
    jwt_sig_public_key: { // allowed formats are jwk | jwks_uri | pem | issuer | metadata_url | raw
        format: 'issuer', // in case of issuer, the issuer value will be taken from jwt payload
        value: null
    },
    ignore_not_before: false, // Optional: controls whether to skip the validation of the nbf claim when validating the ID Token, default is false
    ignore_expiration: false, // Optional: controls whether to skip the validation of the exp claim when validating the ID Token, default is false
    clock_tolerance: 0, // Optional: controls the clock tolerance when validating the ID Token to accomodate drifting clocks, default is 0
    debug: false,  // Optional: Enabling debug to true will display console logs of assistant, default is false
    openid_configuration_url: "https://example.com/path/.well-known/openid-configuration", // Optional: set if the OpenID Configuration URL uses different host or base path than the issuer 
};
```

设置对象的更详细信息可在 [设置](https://npmcn.com/package/%40curity/oauth-assistant/#readme-settings) 节.

将助手导入您的项目, 并使用设置对象初始化 .

```
import Assistant from "@curity/oauth-assistant";
// OR using require 
// const Assistant = require("@curity/oauth-assistant");


const assistant = new Assistant(settings);

assistant.init()
    .then(() => {
        console.log("assistant loaded");
        // Start the authorize flow
    });
```

### 可用方法

```
1. authorize(parameters)
2. authorizeFrame(parameters)
3. authorizeHiddenFrame(parameters)
4. authorizeHiddenFallbackToVisible(parameters)
5. authorizePopup(parameters)
6. authorizeHiddenFallbackToPopup(parameters)
7. getToken()
8. getIDToken()
9. init()
10. refresh()
11. revoke()
12. logout(postLogoutRedirectUri, global)
13. getScope()
14. getExpiresIn()
15. getAdditionalFieds()
16. reset()
```

在初始化助理后,您可以使用任何可用的4个方法开始授权流量.

对于每个授权流,可以像下面这样通过任意数量的可选参数.

```
const parameters = {
    scope: "openid",
    state: "state-value",
    response_type: "token id_token",
   ...
};
```

1.  **登录方向**
    
    ```
    assistant.authorize(parameters); 
    ```
    
2.  **用可见的 Iframe 登录**
    
    ```
    assistant.authorizeFrame(parameters)
     .then((token) => {})
     .catch((err) => {});
    ```
    
3.  **用隐藏的 Iframe 登录**
    
    ```
    assistant.authorizeHiddenFrame(parameters)
     .then((token) => {})
     .catch((err) => {});    
    ```
    
4.  **登录隐藏的 iframe( 如果需要登录, 则返回可见的 iframe)**
    
    ```
    assistant.authorizeHiddenFallbackToVisible(parameters)
     .then((token) => {})
     .catch((err) => {});    
    ```
    
5.  **以可见弹出方式登录**
    
    ```
    assistant.authorizePopup(parameters)
     .then((token) => {})
     .catch((err) => {});
    ```
    
6.  **以隐藏流量登录( 如果需要登录, 回落到可见弹出)**
    
    ```
    assistant.authorizeHiddenFallbackToPopup(parameters)
     .then((token) => {})
     .catch((err) => {});    
    ```
    

一旦授权流量完成,你可以得到 `token`, (中文(简体) ), `id_token` 或使用助理撤销证书.

**获取托肯**

```
assistant.getToken();
```

**获取身份证托肯**

```
assistant.getIDToken();
```

**撤销托肯斯**

```
assistant.revoke()
    .then(() => {})
    .catch((err) => {});
```

**刷新鼠标** 如果AS发布了刷新令牌,则使用它来获得新的令牌.

```
assistant.refresh()
    .then(() => {})
    .catch((err) => {});
```

**注销**  
将用户从服务器上注销并撤销令牌 .  
默认值为 `postLogoutRedirectUri` 实值 `window.location.href`。 。 。 . 默认值为 `global` 实值 `false`,如果设置为 `true` 然后在登录期间作为额外查询参数发送,导致全球所有登录客户端的登录发生.

```
assistant.logout(postLogoutRedirectUri, global)
    .then(() => {})
    .catch((err) => {});
```

**获取瞄准镜**

获取与上次授权响应相关的范围符号的空间限制列表 .

```javascript
assistant.getScope();
```

**进入过期状态**

拿着 `expires_in` 与上次授权响应相关的值.

```javascript
assistant.getExpiresIn();
```

**获取更多字段**

获取与上次授权响应相关的任何附加字段的映射 。 其他字段 `access_token`, (中文(简体) ), `scope`, (中文(简体) ), `expires_in` 或者说 `id_token`。 。 。 .

```javascript
assistant.getAdditionalFields();
```

**重设**

关闭助手打开的任何打开的 Iframe 或弹出, 取消当前登录流 。 该方法可以安全地被调用,如果当前流不支持或使用帧,则不会产生任何效果.

```javascript
assistant.reset();
```

### 设置

在初始化助手时, 您需要在一个包含一些强制和可选值的设置对象中通过 .

```
{
    flow_type      : "code", // Possible values : (code, implicit, assisted_token)
    base_url       : "http://localhost:8443",
    client_id      : "test_client_id",
    issuer         : "https://localhost:8443/oauth/v2/oauth-anonymous",
    redirect_uri   : "http://localhost:8080/assisted.html", // Basic version of assisted.html is available in example/assisted.html but it can be customized as needed.
    for_origin     : "http://localhost:8080",
    iframe         : { // Optional: Passing in null would take default values
        targetElement: null, // targetElement querySelector , default: 'body'
        width   : null, // take default value : 400
        height  : null, // take default value : 700
        style   : null, // take default value
        backdrop: {
            visible      : true, // default is true
            style        : null, // take default value
            backdropClass: ""
        }, 
        extraAttributes: null, //object containing 
    },
    "popup": {
        "width":  null,  // take default value : 400
        "height": null   // take default value : 600
    },
    allowed_origins: ["http://localhost:8443", "http://localhost:8080"], // default is [window.origin]
    disable_session_management: false,
    check_session_iframe: null, // Optional url, if not provided then it will be resolved from metadata
    session_polling_interval: 5, // Optional: polling interval in seconds, default is 5
    check_session_iframe_events: { // Optional
            onStateChanging: () => {},
            onStateChanged: () => {},
            onLogout: () => {},
            onConsent: () => {},
            onError: () => {},
            onUnchanged: () => {},
    },
    allowed_jwt_algorithms: ['RS256'], // Optional: algorithms to trust for JWT validation
    jwt_sig_public_key: { // allowed formats are jwk | jwks_uri | pem | issuer | metadata_url | raw
        format: 'issuer', // in case of issuer, the issuer value will be taken from jwt payload
        value: null
    },
   ignore_not_before: true,
   ignore_expiration: false,
   clock_tolerance: 10,
   debug: false,  // Enabling debug to true will display console logs of assistant
   openid_configuration_url: "https://example.com/path/.well-known/openid-configuration", // Set if the OpenID Configuration URL uses different host or base path than the issuer
};
```

所有标记字段 `*` 是强制性的.

-   **流量 类型**\* 联合国 流程类型决定了要使用的授权流程. 它可以是三种流中的任何一种(代码,隐含,被协助 token).
    
-   **基数url** 授权服务器的基础 URL. 如果省略,则从 `issuer` (发行者 URL 的出处将作为基准 URL). 请注意 `base_url` 或者说 `issuer` 必须设定.
    
-   **客户端( d)**\* App客户端 ID
    
-   **发行者** 这个 `issuer` 授权服务器的值。 请注意 `base_url` 或者说 `issuer` 必须设定.
    
-   **方向调整 uri**\* 发生 `framed flow`这将是类似帮助的东西。 html,以实例提供, 您可以提供任何方向ur,并相应处理响应,就像在援助下所做的那样。 html, (中文(简体) ), 您需要任一主机协助。 html 在您的服务器上, 或者在您身上执行同样的东西, 并相应提供重定向 uri . 如果发生 `login with redirect`,重新定向 uri 可能是您的主机应用程序,或者您要处理响应的任何地方.
    
-   **iframe 图像** 您可以选择自定义 Iframe `height`, (中文(简体) ), `width`, (中文(简体) ), `style` 财务报告和审定财务报表 `backdrop` 如上示例对象所示。 任意 `extraAttributes` 还将增加列入。 添加设置 `iframe` 内 `extraAttributes` (即: `height`, (中文(简体) ), `width` 等)将不会覆盖母对象的值或默认值.
    
-   **弹出** 您可以选择自定义弹出 `height` 财务报告和审定财务报表 `width` 如上示例对象所示.
    
-   **允许的原产地**\* 允许的出处:默认是\[窗口.出处\]。 对于辅助符流,这应当包括令牌服务器的出处或脚本的出处. 如果服务器在倒置代理背后,那么应该使用代理的出处.
    
-   **禁用会话 管理** 设定为已禁用会话管理
    
-   **检查( s)** 检查会话 ifram 的 Url , 默认将从元数据中解决
    
-   **会话( p)** 投票间隔发送信件检查会话 iframe 检查会话, 默认为 5 秒
    
-   **检查 会话 框架 活动**
    
    召回事件,将在检查会话iframe投票时进行.
    
    1.  `onStateChanging` 被称作右前方 `prompt=none` 会话更改时发送.
    2.  `onStateChanged` 被称作右后 `prompt=none` 重新授权后会反馈给客户端.
    3.  `onLogout` 当提示返回错误时调用 `login_required`。 。 。 .
    4.  `onConsent` 当提示返回错误时调用 `consent_required`。 。 。 .
    5.  `onError` 当一个错误被 IP iframe 抛出时调用
    6.  `onUnchanged` 当登录状态不改变时,则称为.
-   **允许 jwt 算法** 可选: JWT 验证的算法
    
-   **jwt sig 公钥** [更多细节](https://www.npmjs.com/package/@curity/jwt-validation#allowed-public-key-formats)
    
    指定用于验证jwt签名的公钥格式和值的可选参数.  
    默认格式是 `issuer`。 。 。 .  
    允许的格式 `jwk` | `jwks_uri` | `pem` | `issuer` | `metadata_url` | `raw`
    
    ```
     1. **jwk**   
        A jwk can directly be passed as an object (and not a string), when format specified is `jwk`.    
        
     2. **jwks_uri**     
        A list of jwks can be retrieved from a specified `jwks_uri`.
     
     3. **pem**    
        A pem key string can be provided using public key format `pem`. 
     
     4. **issuer**   
        If the format specified is `issuer`, then jwt issuer is used to retrieve metadata which in turn, is resolved to retrieve jwk from corresponding jwks_uri. 
       
     5. **metadata_url**   
        If the format specified is `metadata_url`, then jwk is retrieved from corresponding jwks_uri of resolved metadata.
      
     6. **raw**       
        You can provide HMAC secret keys using `raw` format.           
    ```
    
-   **忽略前的( n)** 设定为真以忽略以前未忽略( S)`nbf`在ID Token 有效性检查中,默认为虚假
    
-   **忽略终止( i)** 设置为真到过期( T)`exp`在ID Token 有效性检查中,默认为虚假
    
-   **时钟容忍** 控制时钟 `nbf` 财务报告和审定财务报表 `exp` iD 托肯有效性检查中的索赔
    
-   **调试** 调试模式设置为正则将使助手能够显示控制台日志来帮助调试.
    
-   **打开( c)** OpenID 配置的 URL 众所周知的端点 。 默认情况下, 此 URL 等于发行方值加路径 `/.well-known/openid-configuration`
    

跟随 [https://curity.io/resources/learn/test-using-oauth-assistant/ 互联网档案馆的存檔,存档日期2013-12-02](https://curity.io/resources/learn/test-using-oauth-assistant/) 尝试使用示例应用程序的 OAuth 助手.

## 常见问题

### @curity/oauth-assistant 是什么？

JS OAuth 助理律师

### 如何安装 @curity/oauth-assistant？

在项目目录运行 npm install @curity/oauth-assistant，或使用 pnpm add / yarn add / bun add。

### @curity/oauth-assistant 支持 TypeScript 吗？

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

### @curity/oauth-assistant 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @curity/oauth-assistant 可以商用吗？

@curity/oauth-assistant 使用 UNLICENSED 许可。作者声明为 UNLICENSED，即不授予公开使用许可（与公共领域的 Unlicense 不同）。使用前需获得作者授权。以上为概括，不构成法律意见，请以许可原文为准。

### @curity/oauth-assistant 的下载量有多少？

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

### @curity/oauth-assistant 还在维护吗？

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

