> ## Documentation Index
> Fetch the complete documentation index at: https://docs.didit.me/llms.txt
> Use this file to discover all available pages before exploring further.

# 身份认证快速入门：10 分钟完成首次登录

> 在沙盒应用中开启 Didit 身份认证，通过托管登录页面完成用户登录，并在服务端验证访问令牌。

这篇快速入门将带您在大约 10 分钟内完成 Didit Authentication 的端到端配置。
您将在沙盒应用中注册回调 URL，启用一种登录方式，通过托管登录页面让用户登录，在您的服务器上验证其访问令牌，并在控制台中查看这次登录记录。

## 前提条件

* 一个带有沙盒应用的 Didit 账户。创建账户免费，且每个沙盒应用都已开启认证功能。
* Node.js 20 或更高版本，以及一个可以在 `http://localhost:3000` 上运行的 Web 应用。

## 步骤

**1. 打开您的沙盒应用**

在 [Business Console](https://business.didit.me) 中，使用应用切换器选择您的 **Sandbox** 应用，然后打开 **Authentication**。

沙盒应用接受 `http://localhost` 回调，并接受用于社交登录的 Didit 测试凭据，且从不计费。
生产应用则需要在 **Products** 页面中开启 Authentication：请参阅[准备您的应用](https://docs.didit.me/zh/authentication/overview.md#准备您的应用)。

**2. 注册回调地址和来源**

打开 **Authentication > Security and sessions > Redirect URLs and allowed origins**，并添加：

| 项目 | 值 |
| - | - |
| 重定向 URL | `http://localhost:3000/auth/callback` |
| 允许的来源 | `http://localhost:3000` |

Didit 只会将用户重定向到您已注册的重定向 URL，且须逐字符完全匹配。
允许的来源使浏览器能够与您应用的 Didit 来源交换授权码。

![Didit Business Console 中的重定向 URL 和允许的来源卡片，位于允许列表、阻止列表和登录 URL 旁边](https://mintcdn.com/didit-0f962782/RpqZjIB1GnUPdMTN/images/authentication/console-redirect-urls.png?fit=max\&auto=format\&n=RpqZjIB1GnUPdMTN\&q=85\&s=8bf9cdacf97580097f4e8c6bd242af6f)

重定向 URL 和允许的来源，位于 Authentication > Security and sessions 下。

**3. 开启一种登录方式**

打开 **Authentication > Sign-in methods**，并开启 **Email code**。
新应用默认关闭所有登录方式，托管页面只显示您开启的方式。

如果您愿意，也可以添加 **Passkeys**，或开启使用 **Didit test credentials** 的社交登录方式。这些凭据无需您自己的应用即可在沙盒中使用。
每种登录方式的说明请参阅[登录方式](https://docs.didit.me/zh/authentication/sign-in-methods.md)。

![Didit Business Console 中的 Sign-in methods 页面，包含托管登录页面卡片、无密码和密码登录方式，以及托管页面的实时预览](https://mintcdn.com/didit-0f962782/RpqZjIB1GnUPdMTN/images/authentication/console-sign-in-methods.png?fit=max\&auto=format\&n=RpqZjIB1GnUPdMTN\&q=85\&s=4f71ad0125f22dd8184ad837854ec8db)

Authentication > Sign-in methods，并附带托管页面的实时预览。

**4. 复制您的可发布密钥**

打开 **Authentication > Developers**，并复制 **Publishable key**。
在沙盒应用中，它以 `pk_test_` 开头。

可发布密钥是公开的，它标识您应用的 Didit 登录来源。
切勿将 **Secret key** 放入浏览器或移动端代码中。

**5. 安装 SDK 并登录**

```bash theme={null}
npm install @didit-protocol/auth
```

```ts auth.ts theme={null}
import { createDiditAuth } from "@didit-protocol/auth";

export const auth = createDiditAuth({
  publishableKey: "pk_test_...",
  redirectUri: "http://localhost:3000/auth/callback",
});

// Your sign-in button
export async function onSignInClick() {
  await auth.signIn({ returnTo: "/dashboard" });
}

// Run once on http://localhost:3000/auth/callback
export async function onCallbackPage() {
  const { session, returnTo } = await auth.handleRedirectCallback();
  console.log(session.email, session.vendorData);
  window.location.replace(returnTo ?? "/");
}
```

点击您的按钮：托管页面会要求输入邮箱地址，并发送一个六位数字验证码。
输入验证码后，Didit 会将您带回您的回调地址，回调处理程序会使用一次性验证码换取会话令牌。
使用没有账户的邮箱首次登录时，系统会自动创建账户，因为默认的注册策略允许任何人注册。

![手机上的托管登录页面，包含通行密钥按钮以及邮箱和密码输入框](https://mintcdn.com/didit-0f962782/RpqZjIB1GnUPdMTN/images/authentication/hosted-sign-in-phone.png?fit=max\&auto=format\&n=RpqZjIB1GnUPdMTN\&q=85\&s=842077ff63a6dcffc50b0f0542ab07e4)

手机上的托管登录页面。它只显示您开启的登录方式。

**6. 在服务器上验证令牌**

将 `auth.getToken()` 获取的访问令牌放入 `Authorization` 请求头，发送到您的后端，并在服务器上对每个受保护的请求进行验证：

```ts server.ts theme={null}
import { verifyToken } from "@didit-protocol/auth/server";

export async function authenticate(request: Request) {
  const header = request.headers.get("authorization") ?? "";
  const token = header.startsWith("Bearer ") ? header.slice(7) : "";
  try {
    const claims = await verifyToken(token, { publishableKey: process.env.DIDIT_PUBLISHABLE_KEY });
    return { personId: claims.sub, vendorData: claims.vendor_data };
  } catch {
    return null;
  }
}
```

`verifyToken` 会检查 ES256 签名（使用签发方发布的密钥）、签发方和过期时间。
访问令牌的有效期最长为 5 分钟，`auth.getToken()` 会自动为您刷新它们。
其他语言可以使用[服务器端 SDK](https://docs.didit.me/zh/integration/server-sdks/overview.md) 或任何 JWT 库验证同一令牌，如[令牌和 JWKS](https://docs.didit.me/zh/authentication/tokens-and-jwks.md#在服务器上验证令牌) 所示。

**7. 在控制台中查看登录记录**

打开 **Authentication > Sign-ins**。
您的登录记录会与每个沙盒默认附带的示例登录记录一起列出，并显示结果、方式、设备、位置和风险。
该用户会显示在 **Users** 下。

![Didit Business Console 中的 Sign-ins 页面，列出登录尝试的状态、用户、方式、设备、位置、风险和时间](https://mintcdn.com/didit-0f962782/RpqZjIB1GnUPdMTN/images/authentication/console-sign-ins.png?fit=max\&auto=format\&n=RpqZjIB1GnUPdMTN\&q=85\&s=3c79b4e120c911b732d738e52d1687c8)

Authentication > Sign-ins：所有登录尝试，并可按状态、方式和风险筛选。

如需在服务器上接收登录活动，请将 [Webhook 目标](https://docs.didit.me/zh/integration/webhooks.md)订阅到 `auth.signup` 和 `auth.login`。请参阅[事件和 Webhook](https://docs.didit.me/zh/authentication/events-and-webhooks.md)。

## 上线前

1. 在 **Products** 页面为您的 Live 应用开启 Authentication 功能。
2. 在该页面注册您的生产环境 `https://` 重定向 URL 和来源。Live 应用仅接受 `https://`。
3. 将社交登录中 Didit 的测试凭据替换为您自己应用的客户端 ID 和密钥。
4. 将 Live 可发布密钥（`pk_live_`）复制到您的生产配置中。
5. 按照[上线检查清单](https://docs.didit.me/zh/authentication/integration-guide.md#上线检查清单)逐项完成检查。

## 后续步骤

> [card] [集成指南](https://docs.didit.me/zh/authentication/integration-guide.md)
>
> 托管页面或自有页面、令牌存储、会话、增强验证和故障排查。

> [card] [React 和 Next.js](https://docs.didit.me/zh/authentication/quickstarts/nextjs.md)
>
> 组件、Hooks、HttpOnly Cookie，以及服务端的 `auth()`。

> [card] [iOS、Android、React Native 和 Flutter](https://docs.didit.me/zh/authentication/quickstarts/ios.md)
>
> 通过系统浏览器进行原生登录、通行密钥和受保护的存储。

> [card] [机器人防护](https://docs.didit.me/zh/authentication/bot-protection.md)
>
> 开启可阻止机器人和账户接管的策略。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.