@guardian/identity-auth

中文文档
18.0.0发布于 2026/06/10Apache-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1.6万

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

中文使用文档
文档目录11 节
  1. 浏览器支持
  2. 使用量
  3. 配置
  4. API 密码
  5. authStateManager
  6. tokenManager
  7. token
  8. autoRenew
  9. 类型
  10. 自定义索赔
  11. 捐款

身份认证

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

这个是精细而反向的 奥克塔官方JSDK 这符合守护者的需求.

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

浏览器支持

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

使用量

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 用于遗产身份平台的饼干.

配置

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

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

执行副作用.

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

返回当前认证状态.

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 方法,但没有认证状态.

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

返回当前认证状态.

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

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

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

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

identityAuth.authStateManager.unsubscribe(handler);

tokenManager

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

clear

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

identityAuth.tokenManager.clear();

getTokens

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

  • verifyTokens - 狦 true,在返回之前,将核实这些符号。 默认为 true。 。 。 .
  • refreshIfRequired - 狦 true中,如果符号过期,则会刷新。 默认为 false。 。 。 .
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。 。 。 .

const tokens = identityAuth.tokenManager.getTokensSync();

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

renew

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

返回符号或 undefined。 。 。 .

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

setTokens

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

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

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

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

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

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

类型

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

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[]。 。 。 .

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 共发布 198 个版本,首次发布于 2023/06/08;过去 12 个月发布了 34 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
18.0.0latest2026/06/105 个月前
0.0.0-canary-20260518131757canary2026/05/185 个月前
17.0.02026/05/146 个月前
0.0.0-canary-202604301412582026/04/306 个月前
0.0.0-canary-202604301408592026/04/306 个月前
0.0.0-canary-202604300923262026/04/306 个月前

关于 @guardian/identity-auth 的常见问题

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