@deriv-com/auth-client

中文文档
1.5.8发布于 2025/12/26TypeScriptES Module近 30 天下载 2973
原始使用文档
文档目录15 节
  1. Table of Contents
  2. Getting Started
  3. Prerequisites
  4. Installation
  5. Phase 1: OAuth2 with Hydra
  6. Setting Up Hydra
  7. Using the OAuth2 Hook
  8. Phase 2: OIDC Public Client
  9. Implementation Details
  10. Login Flow
  11. Callback Page
  12. State parameter
  13. Logout Flow
  14. Logout Front Channels
  15. TMB

Auth Client Project

Coverage Status Coveralls Build and Test Release

This project is designed to handle authentication using OAuth2 with Hydra and OIDC. The project is divided into two phases:

  1. Phase 1: OAuth2 with Hydra
  2. Phase 2: OIDC Public Client (coming soon)

Table of Contents

Getting Started

Prerequisites

  • Node.js (>= 14.x)
  • npm (>= 8.x)

Installation

  1. Clone the repository:

    git clone https://github.com/your-username/auth-client.git
    cd auth-client
    
  2. Install dependencies:

    npm install
    
  3. Start the development server:

    npm run dev
    

Phase 1: OAuth2 with Hydra

In this phase, we use OAuth2 with Hydra for authentication.

Setting Up Hydra

  1. Follow the Hydra documentation to set up Hydra in QA box environment.
  2. Configure your OAuth2 settings in the project.

Using the OAuth2 Hook

Use the useOAuth2 hook within your components.

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;

Phase 2: OIDC Public Client

At Deriv, we are implementing Hydra and OpenID Connect (OIDC) to modernize and enhance our authentication and authorization mechanisms. This transition is crucial for ensuring secure, scalable, and standards-compliant access management for our applications and users.

Implementation Details

Most of the setup and implementation is already done in this library in the background. Just need to import a few things are you're good to go.

Login Flow

  • Login button component
import {requestOidcAuthentication } from '@deriv-com/auth-client';

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

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

Callback Page

You would need to create a new route and page for this section in your app. This page will handle the legacy token issuance to the consumer apps.

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;

The tokens returned from the onSignInSuccess will be of this format:

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

You need to convert the tokens into a format that your app understands and works with. Once that’s done, save them securely in localStorage or sessionStorage.

Most of the apps are already set up to look for things like client-accounts or accountsList in storage. If it finds them, it will automatically authorize the user in. Therefore after transforming the tokens and storing them its very crucial to redirect to the main page of your app, so the app can authorize successfully.

Once the legacy tokens are sent to the consumer apps, the library assumes that the user is logged in therefore it sets a cookie called logged_state to true. This will be helpful for the silent login and single logout feature.

Note : The callback page does NOT handle authorize calls. Its sole purpose is to do the access token exchange and return back the legacy tokens to the consumer apps.

State parameter

You can pass in an additional state parameter for payloads to requestOidcAuthentication or requestSilentOidcAuthentication, which will be carried over to the Callback component. You can perform things like passing in an additional redirect_to metadata to inform Callback page where to redirect to next after authentication is completed:

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

And within the Callback component, it will return the state from the onSignInSuccess callback function:

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 = '/';
        }
      }}
    />
  );
};

Logout Flow

This logout process combines two parts: clearing OAuth session cookies through the OAuth2Logout function and running custom cleanup logic specific to your app (like clearing user accounts or tokens). Let’s break it down step-by-step:

  1. This function is provided by the @deriv-com/auth-client library. It uses an iframe to redirect the user to the end session endpoint of the OAuth provider. The main job of OAuth2Logout is to clear any cookies set by the OAuth system during the login session. Your App's Custom Logout Logic.

  2. In addition to clearing OAuth cookies, your app needs to handle its own logout tasks, such as: Logging the user out from the backend (via API or WebSocket calls). Clearing stored user data (like tokens or account information) from localStorage or sessionStorage.

  3. Combining Both The OAuth2Logout function allows you to pass your custom logout logic (called the consumer logout function) as a parameter. Once the OAuth session cookies are cleared, the consumer logout function runs to ensure the user is fully logged out from both the backend (BE) and frontend (FE).

  4. Once the logout is completed, the cookie logged_state will be set to false.

  5. Once the user has succesfully logged out of Hydra, we should revoke their legacy tokens (e.g. a1-...). We can do this by calling the function revokeLegacyTokens and passing in the list of legacy tokens to revoke. Typically you should do this inside your logout handler, which this is invoked after Hydra has successfully logged the user's session out.

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>

Logout Front Channels

Front channels are pages in your application which sole responsibility is to clear local/session storage of your authentication data like client.accounts or loginid when its rendered. This will be used and invoked by OIDC in an iframe during the logout process to log your application out and clear its local/session storage, so that when we land in the application, it will already be in a logged out state. Typically we register front channels under the route /front-channel.

For instance, assume that you are already logged in on Deriv App, SmartTrader and Traders Hub Outsystems, and that these applications have front channels implemented on routes like:

  • https://app.deriv.com/front-channel
  • https://smarttrader.deriv.com/front-channel and
  • https://hub.deriv.com/tradershub/front-channel

Then assume that you are logging out from Deriv.app. When you click the Logout button, in the background Hydra checks any of its registered applications that has the front channels logout route and has a session, and automatically invokes the route using an iframe like:

<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>

Which will automatically clear the local/session storage for authentication data within SmartTrader and Traders Hub Outsystems, so that when the user navigates to SmartTrader or Traders Hub Outsystems, they are already in a logged out state since their client.accounts is already cleared off the local storage.

Once the route and page is implemented, you will need to notify the authentication squad or DevOps to register the front channel logout URI in order for Hydra to invoke it during the logout flow.

TMB

版本与发布记录

@deriv-com/auth-client 共发布 78 个版本,首次发布于 2024/09/10;过去 12 个月发布了 3 个版本。

版本发布日期距今
1.5.8latest2025/12/2610 个月前
1.5.72025/12/2610 个月前
1.5.62025/11/1811 个月前
1.5.52025/10/161.1 年前
1.5.42025/09/021.2 年前
1.5.32025/07/221.3 年前

关于 @deriv-com/auth-client 的常见问题

@deriv-com/auth-client 是什么?

[![Coveralls](https://github.com/deriv-com/auth-client/actions/workflows/coveralls.yml/b

如何安装 @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 和提交记录判断。