# @guardian/identity-auth 中文文档

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

版本：18\.0\.0
npm 元数据更新时间：2026-06-10T10:20:47.462Z
中文译文更新时间：2026-11-17T02:49:30.661Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40guardian/identity-auth
原文对照：https://npmcn.com/package/%40guardian/identity-auth/?lang=original
项目主页：https://github.com/guardian/csnx#readme
源码仓库：https://github.com/guardian/csnx

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

- 包体积（解压后）：153 kB，36 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：@guardian/libs ^33\.0\.0，tslib ^2\.8\.1，typescript ~6\.0\.3
- 首次发布：2023-06-07T17:04:07.112Z
- 最新版本发布：2026-06-10T10:20:47.094Z
- 近 30 天下载量：15521（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：198（近 12 个月 34 个）

## 中文简介

一个用于认证和授权Okta托管的守护者身份平台内用户的图书馆,使用OAuth2和OpenId Connect.

## 安装

```sh
npm install @guardian/identity-auth
```

也可以使用：`pnpm add @guardian/identity-auth`、`yarn add @guardian/identity-auth`、`bun add @guardian/identity-auth`

## README

# 身份认证

一个用于认证和授权Okta托管的守护者身份平台内用户的图书馆,使用OAuth2和OpenId Connect.

这个是精细而反向的 [奥克塔官方JSDK](https://github.com/okta/okta-auth-js) 这符合守护者的需求.

具体而言,它提供了官方SDK功能的子集. 这是为了缩小图书馆的规模,并确保我们只暴露我们需要的功能. 我们的图书馆只使用一些与官方SDK相同的课程和方法,但执行这些课程和方法是我们自己的.

## 浏览器支持

浏览器需要支持以下特性或进行多填充:

-   [`Web Crypto API`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)
    -   [`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)
    -   [`crypto.subtle.digest`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest)
    -   [`crypto.subtle.importKey`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey)
    -   [`crypto.subtle.verify`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/verify)
-   [`TextEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder)
-   [`Page Visibility API`](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API)

## 使用量

```js
import { IdentityAuth } from '@guardian/identity-auth';

// Initialise the library with your configuration values
const identityAuth = new IdentityAuth({
    issuer: 'https://profile.theguardian.com/oauth2/SERVER_ID',
    clientId: 'example-client-id',
    redirectUri: 'https://theguardian.com',
    scopes: ['openid', 'profile'], // and any other scopes you need
});

// Check if the user is logged in and return the current auth state
const authState = await identityAuth.isSignedInWithAuthState();

authState.isAuthenticated; // true or false
authState?.accessToken; // the user's access token object
authState?.idToken; // the user's id token object

// or boolean only
const isLoggedIn = await identityAuth.isSignedIn();

// see rest of API below for more methods
```

应用程序需要在奥克塔注册后才能使用此库. 请联系身份小组 他们会为您提供您需要的配置值 .

一般来说,你使用 _访问托肯_ 代表用户向守护者服务提交 API 请求,您使用 _身份标记_ 读取应用程序中的用户身份信息.

这是取代 `SC_GU_U` 用于遗产身份平台的饼干.

## 配置

```ts
import type { IdentityAuthOptions } from '@guardian/identity-auth';
import { IdentityAuth } from '@guardian/identity-auth';

/**
 * Defines the options that are required to configure the IdentityAuth
 * Ask the Identity team for the values to use for your app.
 *
 * https://developer.okta.com/docs/reference/api/oidc/
 *
 * @param clientId - The client ID of your app
 * @param issuer - The issuer of the tokens
 * @param scopes - The scopes that your app requires
 * @param redirectUri - The redirect URI of your app
 * @param autoRenew - Whether to automatically renew the tokens, defaults to `true`
 * @param renewGracePeriod - The time in seconds before the access token expires to renew the token, defaults to 60 seconds
 * @param idCookieSessionRefresh - If switched on (set to `true`, ), will refresh the okta session and identity cookie (GU_U), if required (once every 30 days), by redirecting the user to `profile`'s `/signin/refresh` endpoint. Should be based on the id-cookie-refresh (idCookieRefresh) switch if being supplied by theguardian.com, defaults to `false`
 * @param oauthTimeout - The time in milliseconds to wait for the OAuth2 authorization code flow to complete, defaults to 30 seconds (30000 milliseconds)
 * @param maxClockSkew - The maximum time drift in seconds between the client and server, defaults to 300 seconds (5 minutes), based on the default maximum tolerance of the Kerberos protocol
 * @param strictClockSkewCheck - If switched on (set to `true`), will throw an error if the clock skew is greater than the `maxClockSkew`, defaults to `false`
 */
const config: IdentityAuthOptions = {
    issuer: 'https://profile.theguardian.com/oauth2/SERVER_ID',
    clientId: 'example-client-id',
    redirectUri: 'https://theguardian.com',
    scopes: ['openid', 'profile'], // and any other scopes you need
    autoRenew: true, // optional, defaults to true
    renewGracePeriod: 60, // optional, defaults to 60 seconds
    idCookieSessionRefresh: false, // optional, defaults to false
    oauthTimeout: 30000, // optional, defaults to 30 seconds (30000 milliseconds)
    maxClockSkew: 300, // optional, defaults to 300 seconds (5 minutes)
    strictClockSkewCheck: false, // optional, defaults to false;
};

const identityAuth = new IdentityAuth(config);
```

## API 密码

`IdentityAuth` 披露如下:

-   [`isSignedInWithAuthState`](https://npmcn.com/package/%40guardian/identity-auth/#readme-issignedinwithauthstate)
-   [`isSignedIn`](https://npmcn.com/package/%40guardian/identity-auth/#readme-issignedin)
-   [`authStateManager`](https://npmcn.com/package/%40guardian/identity-auth/#readme-authstatemanager)
    -   [`getAuthState`](https://npmcn.com/package/%40guardian/identity-auth/#readme-getauthstate)
    -   [`subscribe`](https://npmcn.com/package/%40guardian/identity-auth/#readme-subscribe)
    -   [`unsubscribe`](https://npmcn.com/package/%40guardian/identity-auth/#readme-unsubscribe)
-   [`tokenManager`](https://npmcn.com/package/%40guardian/identity-auth/#readme-tokenmanager)
    -   [`clear`](https://npmcn.com/package/%40guardian/identity-auth/#readme-clear)
    -   [`getTokens`](https://npmcn.com/package/%40guardian/identity-auth/#readme-gettokens)
    -   [`getTokensSync`](https://npmcn.com/package/%40guardian/identity-auth/#readme-gettokenssync)
    -   [`renew`](https://npmcn.com/package/%40guardian/identity-auth/#readme-renew)
    -   [`setTokens`](https://npmcn.com/package/%40guardian/identity-auth/#readme-settokens)
-   [`token`](https://npmcn.com/package/%40guardian/identity-auth/#readme-token)
    -   [`decodeTokens`](https://npmcn.com/package/%40guardian/identity-auth/#readme-decodetokens)
    -   [`getWithoutPrompt`](https://npmcn.com/package/%40guardian/identity-auth/#readme-getwithoutprompt)
    -   [`verifyTokens`](https://npmcn.com/package/%40guardian/identity-auth/#readme-verifytokens)
-   [`autoRenew`](https://npmcn.com/package/%40guardian/identity-auth/#readme-autorenew)
    -   [`start`](https://npmcn.com/package/%40guardian/identity-auth/#readme-start)

#### `isSignedInWithAuthState`

检查用户是否签名, 并在必要时更新认证状态, 返回当前认证状态

执行副作用.

1.  如果用户有一个GU SO cookie, 他们最近签了, 所以我们应该清除他们的符号( 附带效果)
2.  如果用户符号已经存在, 则签名于
3.  如果用户没有代号,但他们有GU U cookie,就会"可能"在其中签名
    -   我们可以尝试获得令牌而无需提醒/重定向用户证书(附带效果)
4.  如果用户没有符号或GU U cookie,则不签名于

返回当前认证状态.

```ts
import { OAuthError } from '@guardian/identity-auth';

try {
    // Check if the user is logged in and return the current auth state
    const authState = await identityAuth.isSignedInWithAuthState();

    console.log(authState.isAuthenticated); // true or false
    console.log(authState?.accessToken); // the user's access token
    console.log(authState?.idToken); // the user's id token

    // e.g. read the id token claims to use in your application
    if (authState.idToken) {
        const claims = authState.idToken.claims;

        console.log('identity id', claims.legacy_identity_id);
        console.log('username', claims.identity_username);
    }

    // e.g use the access token to make an API request
    if (authState.accessToken) {
        const accessTokenString = authState.accessToken.accessToken;

        const response = await fetch('https://some-endpoint.theguardian.com', {
            headers: {
                Authorization: `Bearer ${accessTokenString}`,
            },
        });

        // Handle the response
    }
} catch (error) {
    if (error instanceof OAuthError) {
        // Handle OAuth errors
    }
    // Handle other errors
}
```

#### `isSignedIn`

检查用户是否签名, 返回布尔值 。 与 `isSignedInWithAuthState` 方法,但没有认证状态.

```ts
import { OAuthError } from '@guardian/identity-auth';

// Check if the user is logged in and return a boolean
try {
    const isLoggedIn = await identityAuth.isSignedIn();
} catch (error) {
    if (error instanceof OAuthError) {
        // Handle OAuth errors
    }
    // Handle other errors
}
```

### `authStateManager`

这个 `authStateManager` 是一个实例 `AuthStateManager`,用于管理用户的认证状态.

这个 `IdentityAuthState` 为方便而导出类型.

#### `getAuthState`

返回当前认证状态.

```ts
const authState = identityAuth.authStateManager.getAuthState();

authState.isAuthenticated; // true or false
authState?.accessToken; // the user's access token
authState?.idToken; // the user's id token
```

#### `subscribe`

订阅认证状态的更改 。 每当更改时, 回调会随新的认证状态一同被调用 .

```ts
import type { IdentityAuthState } from '@guardian/identity-auth';

const handler = (authState: IdentityAuthState) => {
    // do something with the new auth state
    console.log(authState);
};

identityAuth.authStateManager.subscribe(handler);
```

#### `unsubscribe`

未订阅给定处理器的认证状态变化 .

```ts
identityAuth.authStateManager.unsubscribe(handler);
```

### `tokenManager`

这个 `tokenManager` 是一个实例 `TokenManager`,用于管理令牌的存储和取回.

#### `clear`

从存储中清除访问权限和标识符 .

```ts
identityAuth.tokenManager.clear();
```

#### `getTokens`

从同步存储中获取令牌,必要时可以刷新并验证令牌. 返回符号或 `undefined`。 。 。 .

-   `verifyTokens` - 狦 `true`,在返回之前,将核实这些符号。 默认为 `true`。 。 。 .
-   `refreshIfRequired` - 狦 `true`中,如果符号过期,则会刷新。 默认为 `false`。 。 。 .

```ts
const tokens = await identityAuth.tokenManager.getTokens({
    verifyTokens: true,
    refreshIfRequired: true,
});

tokens.accessToken; // the user's access token
tokens.idToken; // the user's id token
```

#### `getTokensSync`

从存储同步获取令牌, 不刷新或校验令牌 .

返回符号或 `undefined`。 。 。 .

```ts
const tokens = identityAuth.tokenManager.getTokensSync();

tokens.accessToken; // the user's access token
tokens.idToken; // the user's id token
```

#### `renew`

试图更新代币,无论是否过期

返回符号或 `undefined`。 。 。 .

```ts
const renewedTokens = await identityAuth.tokenManager.renew();
```

#### `setTokens`

在本地存储中设置指使符, 不太可能需要手动使用, 除非您正在手动获取指使符 `token` 课.

```ts
import type { AccessToken, IDToken } from '@guardian/identity-auth';

const accessToken: AccessToken = {
    ...
}
const idToken: IDToken = {
    ...
}

const tokens = {
    accessToken,
    idToken,
};

identityAuth.tokenManager.setTokens(tokens);
```

### `token`

这个 `token` 对象是一个实例 `Token`,它通过执行OAuth授权码与PKCE的流程,交换授权码来管理令牌的取回,并验证ID和访问令牌.

#### `decodeTokens`

解码访问和代号,返回已解码的代号,但不验证其是否有效.

核查还可以通过呼叫 `verifyTokens`。 。 。 .

```ts
import { OAuthError } from '@guardian/identity-auth';

try {
    // tokens from somewhere
    const accessTokenRaw = '...';
    const idTokenRaw = '...';
    const nonce = '...';

    const tokens = identityAuth.token.decodeTokens({
        accessTokenRaw,
        accessTokenClockSkew: 0,
        idTokenRaw,
        idTokenClockSkew: 0,
        nonce,
    });

    await identityAuth.token.verifyTokens(tokens.idToken, tokens.accessToken);
} catch (error) {
    // handle error
    if (error instanceof OAuthError) {
        // handle OAuth error
        error.error; // the error returned by the OAuth server
        error.error_description; // the error description returned by the OAuth server
        error.message; // the error message
    }
    // handle other errors
}
```

#### `getWithoutPrompt`

与 PKCE 执行授权代码流程,将授权代码交换为令牌并验证ID令牌,而不提示用户并使用隐藏的iframe. 回返 `TokenResponse` 或丢出 `OAuthError`。 。 。 .

```ts
import { OAuthError } from '@guardian/identity-auth';

try {
    const tokenResponse = await identityAuth.token.getWithoutPrompt();

    tokenResponse.tokens.accessToken; // the user's access token
    tokenResponse.tokens.idToken; // the user's id token
    tokenResponse.state; // the state parameter passed to the authorize endpoint

    // set the tokens in local storage
    identityAuth.tokenManager.setTokens(tokenResponse.tokens);
} catch (error) {
    // handle error
    if (error instanceof OAuthError) {
        // handle OAuth error
        error.error; // the error returned by the OAuth server
        error.error_description; // the error description returned by the OAuth server
        error.message; // the error message
    }
    // handle other errors
}
```

#### `verifyTokens`

验证身份证,核对签名和索偿,并使用 `at_hash` 由IDToken公司索赔.

-   `idToken` - 身份证明
-   `accessToken` - 核查的出入证

回返 `void` 或丢出 `OAuthError`。 。 。 .

```ts
import { OAuthError } from '@guardian/identity-auth';

try {
    // tokens from somewhere
    const tokens = identityAuth.tokenManager.getTokensSync();

    await identityAuth.token.verifyTokens(tokens.idToken, tokens.accessToken);
} catch (error) {
    // handle error
    if (error instanceof OAuthError) {
        // handle OAuth error
        error.error; // the error returned by the OAuth server
        error.error_description; // the error description returned by the OAuth server
        error.message; // the error message
    }
    // handle other errors
}
```

### `autoRenew`

这个 `autoRenew` 对象是一个实例 `AutoRenew`,它根据符和符的过期时间管理符的自动更新 `autoRenew` 选项(`autoRenew` 财务报告和审定财务报表 `renewGracePeriod`) (中文(简体) ).

#### `start`

开始自动更新令牌,会自动启动,不需要调用,但会被曝光用于其他内部类.

## 类型

为方便起见,我们导出一些类型,这些类型在使用库时可能有用. 更多信息请参见类型本身.

```ts
import type {
    IdentityAuthOptions,
    IdentityAuthState,
    AccessToken,
    AccessTokenClaims,
    CustomClaims,
    IDToken,
    IDTokenClaims,
} from '@guardian/identity-auth';

// also the error which isn't a type, but is useful for checking if an error is an OAuth error
// e.g if (error instanceof OAuthError) { ... }
import { OAuthError } from '@guardian/identity-auth';
```

### 自定义索赔

根据您要求的瞄准镜, 您可以在 Access Token 或 ID Token 中获取自定义请求 。 如果你不为这些索赔创建类型,那么打字符会抱怨不存在.

您可以为您的应用程序添加自定义的主张,为此可以创建扩展 `CustomClaims` 类型.

索赔价值可以是: `string`, (中文(简体) ), `number`, (中文(简体) ), `boolean`, (中文(简体) ), `string[]`, (中文(简体) ), `number[]` 或者说 `boolean[]`。 。 。 .

```ts
type CustomAccessTokenClaims = CustomClaims & {
    foo: string;
};

type CustomIdTokenClaims = CustomClaims & {
    bar: number[];
    baz: boolean;
};

// pass the types to the IdentityAuth class as generics
const auth = new IdentityAuth<CustomAccessTokenClaims, CustomIdTokenClaims>({
    ...
});

// the custom claims will be available on the AccessToken and IDToken types
const authState = auth.authStateManager.getAuthState();

authState.accessToken.foo; // string
authState.idToken.bar; // number[]
authState.idToken.baz; // boolean
```

## 捐款

由于这个库的性质,如果你想修改它,我们建议你先与身份小组谈谈你想要修改的性质,例如关于错误修正,新特性等.

## 常见问题

### @guardian/identity-auth 是什么？

一个用于认证和授权Okta托管的守护者身份平台内用户的图书馆,使用OAuth2和OpenId Connect\.

### 如何安装 @guardian/identity-auth？

在项目目录运行 npm install @guardian/identity-auth，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@guardian/libs（^33\.0\.0）、tslib（^2\.8\.1）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @guardian/identity-auth 支持 TypeScript 吗？

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

### @guardian/identity-auth 支持 ESM 还是 CommonJS？

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

### @guardian/identity-auth 可以商用吗？

@guardian/identity-auth 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @guardian/identity-auth 的下载量有多少？

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

### @guardian/identity-auth 还在维护吗？

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

