@auth0/auth0-auth-js

中文文档
1.18.0发布于 2026/10/21MITTypeScriptESM + CJS构建来源已验证近 30 天下载 839.3万

用于 JavaScript 运行时间的 Auth0 认证客户端 .

中文使用文档
文档目录18 节
  1. 文档
  2. 开始
  3. 1. 安装SDK
  4. 2. 创建 Auth0 SDK 客户端
  5. 3. 构建授权 URL
  6. 4. 建立日志 URL
  7. 5. 托肯交易所
  8. 6. 资源所有人密码赠款
  9. 7. 多功能认证(MFA)
  10. 8. 钥匙
  11. 9. 数据库连接(签名和更改密码)
  12. 10. 数据库连接上的无密码检察官办公室
  13. 11. 更多实例
  14. 反馈
  15. 捐款
  16. 提出问题
  17. 脆弱性报告
  18. 什么是奥特?

这个 @auth0/auth0-auth-js 库提供 API 从 JavaScript 应用程序与 Auth0 认证 Api 交互.

它包含了构建授权 URL 和 登录 URL 的方法, 执行 Backchannel 登录 , 验证一个登录 令牌, 使用授权代码流并刷新 tokens 请求 Tokens, 以及检索一个连接的 Token, 并管理多功能认证( MFA) .

Release Downloads License

📚 文档 - 🚀 开始 - 💬 反馈

文档

  • 实例 - 不同用法的例子.
  • Docs 站点 - 探索我们的文件网站 了解更多关于Auth0.

开始

1. 安装SDK

npm i @auth0/auth0-auth-js

这个库需要Node.js 20 LTS和较新的LTS版本.

2. 创建 Auth0 SDK 客户端

创建实例 AuthClient。此实例将被导入并用于我们需要访问认证方法的任何地方.

import { AuthClient } from '@auth0/auth0-auth-js';

const authClient = new AuthClient({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
});

这个 AUTH0_DOMAIN, (中文(简体) ), AUTH0_CLIENT_ID,以及 AUTH0_CLIENT_SECRET 可从 Auth0 剪贴板 一旦你创建了一个应用程序.

3. 构建授权 URL

构建 URL 以重定向用户代理在 Auth0 请求授权 .

const authClient = new AuthClient({
  // ...
  authorizationParams: {
    redirect_uri: '<AUTH0_REDIRECT_URI>',
  },
  // ...
});

The `AUTH0_REDIRECT_URI` is needed to tell Auth0 what URL to redirect back to after successfull authentication, e.g. `http://localhost:3000/auth/callback`.

[大
您需要注册 AUTH0_REDIRECT_URI 在您的 Auth0 应用程序中 允许召回 URL 通过 Auth0 剪贴板。 。 。 .

为了构建授权 URL, 请调用 buildAuthorizationUrl(),然后将用户重定向到返回的 URL.

const { authorizationUrl, codeVerifier } = await authClient.buildAuthorizationUrl();
  • authorizationUrl: 将用户重定向到的URL.
  • codeVerifier:代码校验器,在交换代码以取出符号时应当存储并使用.

4. 建立日志 URL

构建 URL 以重定向用户代理请求在 Auth0 登录 .

const logoutUrl = authClient.buildLogoutUrl({
  returnTo: '<AUTH0_LOGOUT_RETURN_URL>',
});

[大
您需要注册 AUTH0_LOGOUT_RETURN_URL 在您的 Auth0 应用程序中 允许登录 URL 通过 Auth0 剪贴板。 。 。 .

这个 AUTH0_LOGOUT_RETURN_URL 需要告诉 Auth0 成功日志退出后要返回的 URL . http://localhost:3000。 。 。 .

5. 托肯交易所

SDK支持 RFC 8693 OAuth 2.0 Token Exchange 用于首个在半流量上方,在保持用户身份的同时,允许安全地进行信使交换.

何时使用哪个流程

  • 自定义托肯交换: 当控制主题符号格式时使用。 常见情况:

    • 交换 Auth0 的 MCP 服务器令牌
    • 从遗留的认证系统迁移
    • 与伙伴系统采用自定义符号格式
    • 由您服务单位签发的换证
  • 与 Token Vault 访问托肯交换 (通过) exchangeToken: 交换外部提供者的访问符时使用:

    • 使用用户的 Google 令牌访问 Google API
    • 使用用户的 Facebook 令牌调用 Facebook Graph API
    • Auth0 管理 Token 断层中外部提供者刷新符的任意情景

折旧: getTokenForConnection() 已贬值。 使用 exchangeToken({ connection, subjectToken, subjectTokenType, ... }) 换句话说.

自定义托肯交换示例

说明:在这个SDK中,自定义托肯交换目前需要保密客户端. 支持的客户端认证方法 : client_secret_post, (中文(简体) ), private_key_jwt,以及 mTLS (通过) customFetch) (中文(简体) ). 公共客户尚未获得这种方法的支持.

import { AuthClient } from '@auth0/auth0-auth-js';

const authClient = new AuthClient({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
});

// Exchange a custom token (e.g., from an MCP server or legacy system)
// The subjectTokenType identifies your token format (configured in your Token Exchange Profile)
const response = await authClient.exchangeToken({
  subjectTokenType: 'urn:example:custom-token', // Your custom token type URN
  subjectToken: userAccessToken,                 // The token to exchange
  audience: 'https://api.backend.com',
});

// Handle token expiry - check expiresAt and re-exchange when needed
// Note: expiresAt is in seconds, Date.now() is in milliseconds
const tokenIsValid = Math.floor(Date.now() / 1000) < response.expiresAt;
if (!tokenIsValid) {
  // Re-exchange the token or use a refresh token if available
  const refreshed = await authClient.exchangeToken({
    subjectTokenType: 'urn:example:custom-token',
    subjectToken: newSubjectToken,
    audience: 'https://api.backend.com',
  });
}

安全说明: 决不包括PII、机密或敏感数据 extra 参数. 这些值可由Auth0或中间系统登录. 使用 extra 仅限 非敏感的元数据,如设备ID,会话标识符,或请求上下文.

托肯断层示例

import { AuthClient } from '@auth0/auth0-auth-js';

const authClient = new AuthClient({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
});

// Exchange an Auth0 access token for an external provider's access token (e.g., Google)
const response = await authClient.exchangeToken({
  connection: 'google-oauth2',
  subjectToken: auth0AccessToken,
  subjectTokenType: 'urn:ietf:params:oauth:token-type:access_token',
  loginHint: '[email protected]', // Optional: specify which account when user has multiple
  scope: 'https://www.googleapis.com/auth/calendar.readonly', // Optional: specific scopes
});

// Or exchange an Auth0 refresh token instead
const responseFromRefresh = await authClient.exchangeToken({
  connection: 'google-oauth2',
  subjectToken: auth0RefreshToken,
  subjectTokenType: 'urn:ietf:params:oauth:token-type:refresh_token',
});

// Use the external provider's access token
console.log('External access token:', response.accessToken);
由已贬值的tokenForConnection () 迁移
// ❌ Deprecated (still works, but will be removed in v2.0)
const response = await authClient.getTokenForConnection({
  connection: 'google-oauth2',
  accessToken: auth0AccessToken,
  loginHint: '[email protected]',
});

// ✅ New unified API
const response = await authClient.exchangeToken({
  connection: 'google-oauth2',
  subjectToken: auth0AccessToken,
  subjectTokenType: 'urn:ietf:params:oauth:token-type:access_token',
  loginHint: '[email protected]',
});

学习更多: 自定义托肯交换 | 托肯断层

6. 资源所有人密码赠款

[尖叫声]
这种流动只应来自高度信任的不能进行再定向的应用程序。 如果你可以使用基于方向的应用程序流, 我们建议使用授权代码流.

SDK支持资源所有者密码赠款(ROPG),用于用户通过直接提供用户名和密码进行认证的情景:

const tokenResponse = await authClient.getTokenByPassword({
  username: '[email protected]',
  password: 'password123',
  realm: 'Username-Password-Authentication', // Optional: database connection name
  audience: 'https://api.example.com',        // Optional: API identifier
  scope: 'openid profile email',              // Optional: requested scopes
});

console.log('Access token:', tokenResponse.accessToken);

对于服务器侧应用,您可以通过最终用户的IP地址进行野蛮-武力保护:

const tokenResponse = await authClient.getTokenByPassword({
  username: '[email protected]',
  password: 'password123',
  auth0ForwardedFor: req.ip, // End-user's IP address
});

学习更多: 资源所有者密码流程

7. 多功能认证(MFA)

SDK为管理多功能认证提供内置支持. 您可以注册验证器( OTP, 短信, 电子邮件) , 列出注册验证器, 挑战它们进行验证, 并删除它们 .

// Access the MFA client via the authClient.mfa property
const mfaToken = '<mfa_token_from_mfa_error>';

// Enroll an OTP authenticator (Google Authenticator, Auth0, etc.)
const enrollment = await authClient.mfa.enrollAuthenticator({
  authenticatorTypes: ['otp'],
  mfaToken
});

// List all enrolled authenticators
const authenticators = await authClient.mfa.listAuthenticators({ mfaToken });

// Challenge an authenticator
const challenge = await authClient.mfa.challengeAuthenticator({
  challengeType: 'otp',
  mfaToken
});

// Delete an authenticator
await authClient.mfa.deleteAuthenticator({
  authenticatorId: 'totp|dev_abc123',
  mfaToken
});

外交部的详细例子,包括短信的注册、OOB的挑战,等等,见 外交部的例子。 。 。 .

8. 钥匙

SDK通过WebAuthn协议为基于密码的认证提供本土支持. 你可以注册新的密码,用现有的密码进行认证,并交换密码符的密码证书——都不用基于方向的流量.

import { AuthClient, PasskeyGetTokenError } from '@auth0/auth0-auth-js';

const authClient = new AuthClient({
  domain: '<AUTH0_CUSTOM_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  // Required for getTokenByPasskey() (step 3) — it needs a confidential client.
  // register() and challenge() also work with public clients (no secret).
  clientSecret: '<AUTH0_CLIENT_SECRET>',
});

// 1. Register a new passkey (signup) — works with public or confidential clients
const signupChallenge = await authClient.passkey.register({
  email: '[email protected]',
  name: 'Jane Doe',
});
// Pass signupChallenge.authnParamsPublicKey to navigator.credentials.create()

// 2. Authenticate with an existing passkey (login) — works with public or confidential clients
const loginChallenge = await authClient.passkey.challenge();
// Pass loginChallenge.authnParamsPublicKey to navigator.credentials.get()

// 3. Exchange the serialized credential response for tokens — confidential client only
const tokens = await authClient.passkey.getTokenByPasskey({
  authSession: signupChallenge.authSession,
  credential: serializedCredential,
  audience: 'https://api.example.com',
  scope: 'openid profile email',
});

[大 getTokenByPasskey() 需要一个 保密客户端 (单位:千美元)clientSecret, (中文(简体) ), clientAssertionSigningKey,或毫升 register() 财务报告和审定财务报表 challenge() 与公众客户合作。 对于一个保密的客户, register() 财务报告和审定财务报表 challenge() 需要一个 clientSecret 具体地说,他们没有接受任何其他证书,而且拒绝: client_assertion. 密码还需要下列先决条件:

  • A 类 自定义域 配置于您的 Auth0 租户( 例如 ), auth.example.com没有 example.auth0.com) (中文(简体) ). 自定义域充当了WebAuthn Relying Party (RP) ID,它必须匹配或成为您应用程序起源的可注册域后缀.
  • 数据库连接 passkey 认证方法已启用 .
  • 您的应用程序必须在一个与配置的 RP ID 匹配的域上通过 HTTPS 服务 .

详细的密码示例,包括证书序列化、所有参数选项和错误处理,参见 密码。 。 。 .

学习更多: 密码 | 本地 Passkeys API 密码

9. 数据库连接(签名和更改密码)

SDK提供数据库客户端,用于针对 Auth0 的自助注册和密码更改请求 数据库连接 (例如 Username-Password-Authentication) (中文(简体) ). 数据库客户端可通过 authClient.database 属性.

import { AuthClient, SignUpError, ChangePasswordError } from '@auth0/auth0-auth-js';

const authClient = new AuthClient({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
});

// 1. Register a new user
try {
  const user = await authClient.database.signUp({
    email: '[email protected]',
    password: 'a-Str0ng-Password!',
    connection: 'Username-Password-Authentication',
    // Optional profile fields: username, givenName, familyName, name, nickname, picture, userMetadata
  });
  console.log(user.id); // normalized identifier; may be undefined if the server omits one
} catch (error) {
  if (error instanceof SignUpError) {
    console.error(error.code, error.message, error.cause); // e.g. 'invalid_password'
  }
}

// 2. Request a password-change email
try {
  const message = await authClient.database.changePassword({
    email: '[email protected]', // or `username: 'jane'` for username-only connections
    connection: 'Username-Password-Authentication',
    // Optional: organization
  });
  console.log(message); // plain-text confirmation from the server
} catch (error) {
  if (error instanceof ChangePasswordError) {
    console.error(error.code, error.message);
  }
}

[大 这些行动称为 /dbconnections/signup 财务报告和审定财务报表 /dbconnections/change_password 终点,即 公开 仅限 clientId 从不泄露客户秘密 他们与公众和保密客户合作. changePassword 返回 a 纯文本 确定字符串,而不是 JSON, 并且永远不要显示电子邮件是否匹配已有用户 。 两种方法都接受可选的每个请求 clientId 超过.

包括所有参数选项和错误处理的详细示例,请参见 数据库连接示例。 。 。 .

学习更多: 数据库连接 | 更改用户密码

10. 数据库连接上的无密码检察官办公室

对于使用数据库连接(而不是专用的无密码连接)的应用程序,SDK支持嵌入式OTP挑战流:

// Step 1: Request an OTP challenge
const challenge = await authClient.passwordless.challengeWithEmail({
  email: '[email protected]',
  connection: 'my-db-connection',
});

// Step 2: Exchange the OTP for tokens
const tokens = await authClient.passwordless.getTokenByPasswordlessDbConnection({
  authSession: challenge.authSession,
  otp: userEnteredCode,
  scope: 'openid profile',
});

电话检察官办公室也通过下列方式得到支持: challengeWithPhoneNumber见 数据库连接上的无密码检察官办公室 详细错误处理、外交部整合和租户先决条件的例子.

11. 更多实例

实例的完整概述可见于 缩略语.md。 。 。 .

反馈

捐款

我们赞赏反馈和对这次再投资的贡献! 在开始前,请阅读以下内容:

提出问题

请提供反馈或报告错误 提出我们的问题追踪器。 。 。 .

脆弱性报告

请不要在公共 GitHub 问题跟踪器上报告安全漏洞 。 这个 负责任的披露程序 详细说明披露安全问题的程序.

什么是奥特?

Auth0 Logo

Auth0是一个易于执行,可适应的认证和授权平台. 学习更多退房 为什么是Auth0?

这个项目根据麻省理工学院的许可证获得许可。 见 自由主义 需要更多信息的文件.

版本与发布记录

@auth0/auth0-auth-js 共发布 25 个版本,首次发布于 2025/03/28;过去 12 个月发布了 20 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.18.0latest2026/10/2117 天前
1.17.02026/10/1424 天前
1.16.12026/10/021 个月前
1.16.02026/09/291 个月前
1.15.02026/09/111 个月前
1.14.02026/09/081 个月前

关于 @auth0/auth0-auth-js 的常见问题

@auth0/auth0-auth-js 是什么?

用于 JavaScript 运行时间的 Auth0 认证客户端 .

如何安装 @auth0/auth0-auth-js?

在项目目录运行 npm install @auth0/auth0-auth-js,或使用 pnpm add / yarn add / bun add。

@auth0/auth0-auth-js 支持 TypeScript 吗?

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

@auth0/auth0-auth-js 支持 ESM 还是 CommonJS?

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

@auth0/auth0-auth-js 可以商用吗?

@auth0/auth0-auth-js 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@auth0/auth0-auth-js 的下载量有多少?

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

@auth0/auth0-auth-js 还在维护吗?

最新版本 1.18.0 发布于 2026/10/21(17 天前);至今共发布 25 个版本,其中过去 12 个月发布了 20 个;首次发布于 2025/03/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。