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

# 身份验证

> 了解如何使用 KillB API 进行身份验证

## 概述

KillB API 使用 **JWT（JSON Web Tokens）** 进行身份验证。所有 API 请求必须在 Authorization 标头中包含有效的访问令牌。

<Info>
  API 身份验证使用 **电子邮件/密码** 登录和 **API 密钥** 的组合，用于不同的访问模式。
</Info>

## 身份验证方法

<Tabs>
  <Tab title="JWT 令牌（主要）">
    用于大多数 API 操作。通过登录端点获取。

    **最适合：** Web 和移动应用程序、用户特定操作
  </Tab>

  <Tab title="API 密钥">
    用于服务器到服务器的操作和 webhooks。

    **最适合：** 后端服务、管理操作
  </Tab>
</Tabs>

## 获取您的凭证

1. 在 [https://otc.killb.com/auth/jwt/register](https://otc.killb.com/auth/jwt/register) **注册** KillB 账户
2. 在 [otc.killb.com](https://otc.killb.com) **访问门户**
3. **获取凭证：**
   * 您的登录电子邮件和密码
   * 从门户设置中获取您的 API 密钥

## 登录流程

### 步骤 1：生成访问令牌

```bash theme={null}
POST /api/v2/auth/login
```

**请求：**

```json theme={null}
{
  "email": "your-email@example.com",
  "password": "your-password"
}
```

**响应：**

```json theme={null}
{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresIn": 3600000,
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

<CodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://sandbox.killb.app/api/v2/auth/login \
    --header 'Content-Type: application/json' \
    --data '{
      "email": "your-email@example.com",
      "password": "your-password"
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://sandbox.killb.app/api/v2/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: 'your-email@example.com',
      password: 'your-password'
    })
  });

  const data = await response.json();
  const accessToken = data.accessToken;
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://sandbox.killb.app/api/v2/auth/login',
      json={
          'email': 'your-email@example.com',
          'password': 'your-password'
      }
  )

  data = response.json()
  access_token = data['accessToken']
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init('https://sandbox.killb.app/api/v2/auth/login');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
      'email' => 'your-email@example.com',
      'password' => 'your-password'
  ]));
  curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

  $response = curl_exec($ch);
  $data = json_decode($response, true);
  $accessToken = $data['accessToken'];
  ?>
  ```
</CodeGroup>

### 步骤 2：使用访问令牌

在所有 API 请求的 `Authorization` 标头中包含访问令牌：

```bash theme={null}
Authorization: Bearer YOUR_ACCESS_TOKEN
```

**示例请求：**

```bash theme={null}
curl --request GET \
  --url https://sandbox.killb.app/api/v2/users \
  --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
```

## 刷新令牌

访问令牌在 1 小时后过期。使用刷新令牌获取新的访问令牌：

```bash theme={null}
POST /api/v2/auth/refresh
```

**请求：**

```json theme={null}
{
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

**响应：**

```json theme={null}
{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresIn": 3600000
}
```

<CodeGroup>
  ```javascript Node.js theme={null}
  async function refreshAccessToken(refreshToken) {
    const response = await fetch('https://sandbox.killb.app/api/v2/auth/refresh', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ refreshToken })
    });
    
    const data = await response.json();
    return data.accessToken;
  }
  ```

  ```python Python theme={null}
  def refresh_access_token(refresh_token):
      response = requests.post(
          'https://sandbox.killb.app/api/v2/auth/refresh',
          json={'refreshToken': refresh_token}
      )
      data = response.json()
      return data['accessToken']
  ```
</CodeGroup>

<Tip>
  在您的应用程序中实现自动令牌刷新，以保持不间断的 API 访问。
</Tip>

## 安全最佳实践

<AccordionGroup>
  <Accordion title="安全存储凭证" icon="lock">
    * 永远不要将凭证提交到版本控制
    * 使用环境变量存储 API 密钥和令牌
    * 定期轮换 API 密钥
    * 使用密钥管理服务（AWS Secrets Manager、HashiCorp Vault 等）
  </Accordion>

  <Accordion title="令牌管理" icon="clock">
    * 安全存储令牌（加密存储、安全 cookie）
    * 实现自动令牌刷新
    * 注销时清除令牌
    * 设置适当的令牌过期时间
  </Accordion>

  <Accordion title="网络安全" icon="shield">
    * 始终对 API 请求使用 HTTPS
    * 为移动应用实现证书固定
    * 验证 SSL 证书
    * 使用安全网络连接
  </Accordion>

  <Accordion title="错误处理" icon="triangle-exclamation">
    * 不要向最终用户暴露身份验证错误
    * 记录身份验证失败以进行监控
    * 对登录尝试实施速率限制
    * 优雅地处理令牌过期
  </Accordion>
</AccordionGroup>

## 身份验证错误

常见的身份验证错误响应：

| 状态代码  | 错误   | 描述        |
| ----- | ---- | --------- |
| `401` | 未授权  | 无效或过期的令牌  |
| `403` | 禁止   | 有效令牌但权限不足 |
| `400` | 错误请求 | 无效的凭证格式   |

**示例错误响应：**

```json theme={null}
{
  "errorCode": "AUTH.0001",
  "message": ["Invalid credentials"],
  "statusCode": "401"
}
```

## 测试身份验证

使用沙盒环境测试身份验证：

**沙盒 URL：** `https://sandbox.killb.app`

<Tip>
  为沙盒测试创建单独的测试账户。沙盒凭证在生产环境中不起作用。
</Tip>

## 示例：完整的身份验证流程

这是一个管理身份验证状态的完整示例：

<CodeGroup>
  ```javascript Node.js theme={null}
  class KillBAuth {
    constructor(email, password) {
      this.email = email;
      this.password = password;
      this.accessToken = null;
      this.refreshToken = null;
      this.baseUrl = 'https://sandbox.killb.app';
    }

    async login() {
      const response = await fetch(`${this.baseUrl}/api/v2/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: this.email,
          password: this.password
        })
      });

      const data = await response.json();
      this.accessToken = data.accessToken;
      this.refreshToken = data.refreshToken;
      return data;
    }

    async refresh() {
      const response = await fetch(`${this.baseUrl}/api/v2/auth/refresh`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          refreshToken: this.refreshToken
        })
      });

      const data = await response.json();
      this.accessToken = data.accessToken;
      this.refreshToken = data.refreshToken;
      return data;
    }

    getAuthHeaders() {
      return {
        'Authorization': `Bearer ${this.accessToken}`,
        'Content-Type': 'application/json'
      };
    }
  }

  // Usage
  const auth = new KillBAuth('your-email@example.com', 'your-password');
  await auth.login();

  // Make authenticated request
  const response = await fetch(`${auth.baseUrl}/api/v2/users`, {
    headers: auth.getAuthHeaders()
  });
  ```

  ```python Python theme={null}
  import requests
  from datetime import datetime, timedelta

  class KillBAuth:
      def __init__(self, email, password):
          self.email = email
          self.password = password
          self.access_token = None
          self.refresh_token = None
          self.expires_at = None
          self.base_url = 'https://sandbox.killb.app'
      
      def login(self):
          response = requests.post(
              f'{self.base_url}/api/v2/auth/login',
              json={'email': self.email, 'password': self.password}
          )
          data = response.json()
          self.access_token = data['accessToken']
          self.refresh_token = data['refreshToken']
          self.expires_at = datetime.now() + timedelta(milliseconds=data['expiresIn'])
          return data
      
      def refresh(self):
          response = requests.post(
              f'{self.base_url}/api/v2/auth/refresh',
              json={'refreshToken': self.refresh_token}
          )
          data = response.json()
          self.access_token = data['accessToken']
          self.refresh_token = data['refreshToken']
          self.expires_at = datetime.now() + timedelta(milliseconds=data['expiresIn'])
          return data
      
      def get_auth_headers(self):
          if datetime.now() >= self.expires_at:
              self.refresh()
          return {'Authorization': f'Bearer {self.access_token}'}

  # Usage
  auth = KillBAuth('your-email@example.com', 'your-password')
  auth.login()

  # Make authenticated request
  response = requests.get(
      f'{auth.base_url}/api/v2/users',
      headers=auth.get_auth_headers()
  )
  ```
</CodeGroup>

## 下一步

<CardGroup cols={2}>
  <Card title="支持的网络" icon="network-wired" href="/zh/supported-networks">
    了解可用的支付方式和区块链网络
  </Card>

  <Card title="创建您的第一个用户" icon="user-plus" href="/zh/guides/users/create-user">
    通过创建用户配置文件开始构建
  </Card>
</CardGroup>
