# @deriv-com/auth-client 中文文档

规范地址：https://npmcn.com/package/%40deriv-com/auth-client/

版本：1\.5\.8
npm 元数据更新时间：2025-12-26T02:16:49.313Z
中文译文更新时间：2026-11-12T04:23:07.128Z
软件包许可：未声明

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

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

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

- 包体积（解压后）：643 kB，46 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2024-09-10T03:50:31.540Z
- 最新版本发布：2025-12-26T02:16:49.027Z
- 近 30 天下载量：2973（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：78（近 12 个月 3 个）

## 中文简介

[![Coverage Status](https://coveralls.io/repos/github/deriv-com/auth-client/badge.svg?branch=master)](https://coveralls.io/github/deriv-com/auth-client?branch=master) \[\[颂\] (出[https://github.com/deriv-com/auth-client/actions/workflows/coveralls.yml/b 互联网档案馆的存檔,存档日期2013-12-22](https://github.com/deriv-com/auth-client/actions/workflows/coveralls.yml/b)

## 安装

```sh
npm install @deriv-com/auth-client
```

也可以使用：`pnpm add @deriv-com/auth-client`、`yarn add @deriv-com/auth-client`、`bun add @deriv-com/auth-client`

## README

# Auth 客户端项目

[![Coverage Status](https://coveralls.io/repos/github/deriv-com/auth-client/badge.svg?branch=master)](https://coveralls.io/github/deriv-com/auth-client?branch=master) [![Coveralls](https://github.com/deriv-com/auth-client/actions/workflows/coveralls.yml/badge.svg)](https://github.com/deriv-com/auth-client/actions/workflows/coveralls.yml) [![Build and Test](https://github.com/deriv-com/auth-client/actions/workflows/build.yml/badge.svg)](https://github.com/deriv-com/auth-client/actions/workflows/build.yml) [![Release](https://github.com/deriv-com/auth-client/actions/workflows/publish_npm.yml/badge.svg)](https://github.com/deriv-com/auth-client/actions/workflows/publish_npm.yml)

这个项目旨在与Hydra和OIDC处理使用OAuth2的认证. 该项目分为两个阶段:

1.  **第1阶段**: OAuth2 与 Hydr
2.  **第2阶段**OIDC 公共客户端(即将到来)

## 目录

-   [开始](https://npmcn.com/package/%40deriv-com/auth-client/#readme-getting-started)
-   [项目结构](https://npmcn.com/package/%40deriv-com/auth-client/#readme-project-structure)
-   [第1阶段:OAuth2与海德拉](https://npmcn.com/package/%40deriv-com/auth-client/#readme-phase-1-oauth2-with-hydra)
-   [阶段2: OIDC 公共客户端](https://npmcn.com/package/%40deriv-com/auth-client/#readme-phase-2-oidc-public-client)

## 开始

### 先决条件

-   节点.js (>= 14.x)
-   npm (>= 8.x) (中文(简体) )

### 安装

1.  清除仓库 :
    
    ```sh
    git clone https://github.com/your-username/auth-client.git
    cd auth-client
    ```
    
2.  安装依赖性 :
    
    ```sh
    npm install
    ```
    
3.  启动开发服务器 :
    
    ```sh
    npm run dev
    ```
    

## 第1阶段:OAuth2与海德拉

在这个阶段,我们使用OAuth2和Hydra进行认证.

### 设置水母

1.  跟着 [水文学文献](https://service-auth.deriv.team/resources/hydra-qa-setup/) 在QA盒环境中设置海德拉.
2.  在工程中配置您的 OAuth2 设置 .

### 使用 OAuth2 钩

使用 `useOAuth2` 钩入你的组件.

```typescript
import React from 'react';
import { useOAuth2 } from '@deriv-com/auth-client';

const YourComponent = () => {

    const { logout } = useAuthData(); // Your custom hook or function to handle logout

    const WSLogoutAndRedirect = async () => {
        await logout();
        // Redirect or perform any additional actions here
    };

    const { OAuth2Logout } = useOAuth2(WSLogoutAndRedirect);

    return (
        <div>
            <button onClick={OAuth2Logout}>Logout</button>
        </div>
    );
};

export default YourComponent;

```

## 阶段2: OIDC 公共客户端

在Deriv,我们正在实施Hydra和OpenID连接(OIDC),以更新和加强我们的认证和授权机制。 这种过渡对于确保我们的应用程序和用户的安全、可扩展和符合标准的接入管理至关重要.

### 执行细节

在背景中,大部分设置和执行已经在这个图书馆完成. 只是需要进口一些东西 你可以走了.

### 登录流量

-   登录按钮组件

```typescript
import {requestOidcAuthentication } from '@deriv-com/auth-client';

 const handleLogin = async () => {
      await requestOidcAuthentication({
        redirectCallbackUri: `${window.location.origin}/callback`,
      });
  };

<button onClick={handleLogin}>Login</button>
```

### 回拨页面

您需要在您的应用程序中创建此部分的新路线和页面 。 此页面将处理遗留给消费者应用的代币发行.

```typescript
import React from 'react';
import { Callback } from '@deriv-com/auth-client';
import { transformAccountsFromResponseBody } from '@site/src/utils';
import useAuthContext from '@site/src/hooks/useAuthContext';

const CallbackPage = () => {
  const { updateLoginAccounts } = useAuthContext();

  return (
    <Callback
      onSignInSuccess={(tokens) => {
        const accounts = transformAccountsFromResponseBody(tokens);

        updateLoginAccounts(accounts);

        window.location.href = '/';
      }}
    />
  );
};

export default CallbackPage;
```

从 signInSuccess 上返回的符号将使用此格式 :

```typescript
{
  acct1: 'CR123123',
  curr1: 'USD',
  token1: 'a1-zxcnzxchzxc1'
  acct2: 'CR998989',
  curr2: 'EUR',
  token2: 'a1-fidifdf0991',
  ...
}
```

您需要将符号转换为您的应用程序能理解和工作的格式 。 一旦完成,就安全地保存在本地Storage或会话Storage中.

大部分的应用程序已经设置,以寻找客户端账户或存储中的账户列表等内容. 如果发现它们,它会自动授权用户进入. 因此,在转换了符号并将其存储后,它对于重定向到您应用的主页非常重要,因此应用可以成功授权.

一旦遗留的代号被发送到消费者应用程序,库会假设用户被登录,因此它设置一个叫"locked state"的饼干为真. 这将有利于无声登录和单一登录功能.

注:回调页面不处理授权调用. 其唯一目的是进行访问符交换,并将遗留的符回给消费者应用.

## 状态参数

您可以在附加状态参数中通过有效载荷到 `requestOidcAuthentication` 或者说 `requestSilentOidcAuthentication`,将结转至 `Callback` 组件。 你可以做一些事情,比如通过一个额外的 `redirect_to` 要告知的元数据 `Callback` 在认证完成后重定向到下一个位置的页面 :

```
  requestOidcAuthentication({
    redirectCallbackUri: `${window.location.origin}/callback`,
    state: {
      redirect_to: '/tradershub/home'
    }
  });
```

和内部 `Callback` 组件,它将返回状态从 `onSignInSuccess` 回调函数 :

```
const CallbackPage = () => {
  const { updateLoginAccounts } = useAuthContext();

  return (
    <Callback
      onSignInSuccess={(tokens, state) => {
        const accounts = transformAccountsFromResponseBody(tokens);

        updateLoginAccounts(accounts);

        const redirectTo = (state as Record<string, any>)?.redirect_to;
        if (redirectTo) {
          window.location.href = redirectTo;
        } else {
          window.location.href = '/';
        }
      }}
    />
  );
};
```

## 注销流程

这个登出程序结合了两部分:通过 OAuth2Logout 函数清除 OAuth会话 cookie , 并运行针对您的应用程序的自定义清除逻辑( 如清除用户账户或令牌) 。 让我们分解一下:

1.  此功能由@deriv-com/auth-client 库提供. 它使用iframe将用户重定向到OAuth提供者的会话结束点. OAuth2Logout的主要工作是在登录会话中清除由OAuth系统设置的任何饼干. 您的 App 自定义登录逻辑 .
    
2.  除了清除OAuth cookie外,您的应用程序还需要处理自己的登录任务,例如: 从后端登录用户(通过API或WebSocket呼叫). 从本地Storage或SessionStorage中清除所储存的用户数据(如指针或账户信息).
    
3.  组合两个 OAuth2Logout 函数可以将您的自定义登录逻辑(称为消费者登录函数)作为参数传递. OAuth会话 cookie 清空后,消费者登出功能会运行,以确保用户从后端(BE)和前端(FE)被完全记录出.
    
4.  登录完成后, cookie 登录 state 将被设定为虚假 .
    
5.  一旦用户顺利地登录出Hydra,我们就应该撤销他们的遗迹(例如a1-. 我们可以调用这个功能 `revokeLegacyTokens` 并传递在遗迹列表中 以废除。 通常您应该在您的登录处理器中这样做, 在 Hydra 成功记录了用户的会话后, 才会引用 .
    

```typescript
import { OAuth2Logout, revokeLegacyTokens } from '@deriv-com/auth-client';

// we clean up everything related to the user here, for now it's just user's account
// later on we should clear user tokens as well
const logout = useCallback(async () => {
    const clientAccounts = localStorage.getItem('client.accounts') || []
    const tokens = Object.values(clientAccounts).map(account => account.token);
    // revoke the legacy tokens,
    await revokeLegacyTokens(tokens);
    // then call your application's post-logout cleanup functions
    await apiManager.logout();
    updateLoginAccounts([]);
    updateCurrentLoginAccount({
      name: '',
      token: '',
      currency: '',
    });
}, [updateCurrentLoginAccount, updateLoginAccounts]);

const handleLogout = () => {
    OAuth2Logout(logout);
};

// In your button
<button onClick={handleLogout}>Logout</button>
```

## 关闭前频道

前方渠道是您的应用程序中的页面, 唯一的责任是清除您认证数据的本地/会话存储, 如 `client.accounts` 或者说 `loginid` 当它变成。 这将会被OIDC在登录过程中在一个iframe中被使用和引用,以登录您的应用程序并清除其局部/会话存储,这样当我们降落在应用程序中时,它就已经处于被登录状态了. 通常我们会在路线下登记前台 `/front-channel`。 。 。 .

例如,假设您已经登录到Deriv App、Smart Trader和Traders Hub Outsystems上,而且这些应用程序在以下线路上安装了前台频道:

-   `https://app.deriv.com/front-channel`
-   `https://smarttrader.deriv.com/front-channel` 财务报告和审定财务报表
-   `https://hub.deriv.com/tradershub/front-channel`

假设你在Deriv. app上记录下来 当点击日志按钮时,在背景 Hydra 中检查其注册过的任何具有前频道日志路径并有会话的应用程序,并使用iframe 等自动引用路径:

```
<iframe src="https://app.deriv.com/front-channel?iss=https://oauth.deriv.com&sid=..."></iframe>
<iframe src="https://smarttrader.deriv.com/front-channel?iss=https://oauth.deriv.com&sid=..."></iframe>
<iframe src="https://hub.deriv.com/tradershub/front-channel?iss=https://oauth.deriv.com&sid=..."></iframe>
```

这将自动清除SmartTrader和Traders Hub Outsystems中用于认证数据的本地/会话存储,这样当用户导航到SmartTrader或Traders Hub Outsystems时,它们已经处于关闭状态 `client.accounts` 已经清除了本地仓库.

一旦路径和页面被执行,您需要通知认证小组或DevOps注册前频道登录URI,以便Hydra在登录流量中引用.

## TMB 主题

## 常见问题

### @deriv-com/auth-client 是什么？

\[\[颂\] \(出https://github\.com/deriv-com/auth-client/actions/workflows/coveralls\.yml/b 互联网档案馆的存檔,存档日期2013-12-22

### 如何安装 @deriv-com/auth-client？

在项目目录运行 npm install @deriv-com/auth-client，或使用 pnpm add / yarn add / bun add。

### @deriv-com/auth-client 支持 TypeScript 吗？

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

### @deriv-com/auth-client 支持 ESM 还是 CommonJS？

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

### @deriv-com/auth-client 可以商用吗？

@deriv-com/auth-client 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @deriv-com/auth-client 的下载量有多少？

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

### @deriv-com/auth-client 还在维护吗？

最新版本 1\.5\.8 发布于 2025/12/26（10 个月前）；至今共发布 78 个版本，其中过去 12 个月发布了 3 个；首次发布于 2024/09/10。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

