# @deliverart/sdk-js-authentication 中文文档

规范地址：https://npmcn.com/package/%40deliverart/sdk-js-authentication/

版本：3\.0\.1
npm 元数据更新时间：2026-11-10T20:25:34.359Z
中文译文更新时间：2026-11-12T02:52:00.361Z
软件包许可：未声明

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

原始 npm 页面：https://www.npmjs.com/package/%40deliverart/sdk-js-authentication
原文对照：https://npmcn.com/package/%40deliverart/sdk-js-authentication/?lang=original

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

- 包体积（解压后）：14.7 kB，6 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2025-06-17T07:06:00.350Z
- 最新版本发布：2026-11-10T20:25:34.186Z
- 近 30 天下载量：3158（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：319（近 12 个月 230 个）

## 中文简介

交付艺术 SDK 认证模块

## 安装

```sh
npm install @deliverart/sdk-js-authentication
```

也可以使用：`pnpm add @deliverart/sdk-js-authentication`、`yarn add @deliverart/sdk-js-authentication`、`bun add @deliverart/sdk-js-authentication`

## README

# @ deliverart/ sdk-js- 认证

交付艺术JavaScript SDK的认证插件. 在所有API请求中自动添加 Bearer 令牌认证.

## 安装

```bash
npm install @deliverart/sdk-js-authentication @deliverart/sdk-js-core
# or
pnpm add @deliverart/sdk-js-authentication @deliverart/sdk-js-core
# or
yarn add @deliverart/sdk-js-authentication @deliverart/sdk-js-core
```

## 导出类型

### 认证 插件

```typescript
class AuthenticationPlugin implements ApiClientPlugin<AuthenticationExtension>
```

在所有API请求中添加 JWT Bearer 令牌认证的插件 .

**构造器 :**

-   `constructor(config: AuthenticationConfig)`

### 认证配置

```typescript
interface AuthenticationConfig {
  getAccessToken: () => Promise<string | null>
}
```

认证插件的配置对象 .

**属性 :**

-   `getAccessToken: () => Promise<string | null>` (需要) - 返回访问符的 Async 函数, 如果未认证则无效

### 认证扩展

```typescript
interface AuthenticationExtension extends ApiExtension {
  authentication: {
    enable: () => void;
    disable: () => void;
  }
}
```

插件安装时添加到API客户端中.

**方法:**

-   `enable()` - 启用认证( 对请求添加授权头)
-   `disable()` - 禁用认证(skips 添加授权头)

### 错误

#### 认证错误

```typescript
class AuthenticationError extends Error
```

当需要认证时抛出,但没有访问令牌可用.

## 使用量

### 基本设置

```typescript
import { createApiClient } from '@deliverart/sdk-js-core';
import { AuthenticationPlugin } from '@deliverart/sdk-js-authentication';

const getAccessToken = async (): Promise<string | null> => {
  // Retrieve token from your storage
  return localStorage.getItem('accessToken');
};

const client = createApiClient({ 
  baseUrl: 'https://api.deliverart.com' 
})
  .addPlugin(new AuthenticationPlugin({ getAccessToken }));
```

**参数:**

-   `getAccessToken` (需要) - 获取当前访问符的函数

### 使用不同的托肯存储

#### 本地服务器

```typescript
const getAccessToken = async (): Promise<string | null> => {
  return localStorage.getItem('accessToken');
};
```

#### 会话集

```typescript
const getAccessToken = async (): Promise<string | null> => {
  return sessionStorage.getItem('accessToken');
};
```

#### 饼干

```typescript
import Cookies from 'js-cookie';

const getAccessToken = async (): Promise<string | null> => {
  return Cookies.get('accessToken') ?? null;
};
```

#### Next.js 有服务器动作

```typescript
import { cookies } from 'next/headers';

const getAccessToken = async (): Promise<string | null> => {
  const cookieStore = await cookies();
  return cookieStore.get('accessToken')?.value ?? null;
};
```

#### Auth 提供者(例如 Auth0, 办事员)

```typescript
import { useAuth } from '@clerk/nextjs';

const getAccessToken = async (): Promise<string | null> => {
  const { getToken } = useAuth();
  return await getToken();
};
```

### 启用/禁用认证

```typescript
// Disable authentication temporarily
client.authentication.disable();

// Make unauthenticated requests
await client.call(new PublicRequest());

// Re-enable authentication
client.authentication.enable();

// Make authenticated requests
await client.call(new ProtectedRequest());
```

**使用大小写 :**

-   不需要认证的公用端点
-   来宾离职流量
-   登记/登记申请

### 带有下个.js的完整示例

```typescript
// lib/sdk/client.ts
import { createApiClient, type ApiClient } from '@deliverart/sdk-js-core';
import { AuthenticationPlugin } from '@deliverart/sdk-js-authentication';
import { ErrorHandlerPlugin } from '@deliverart/sdk-js-error-handler';

const getAccessToken = async (): Promise<string | null> => {
  // Server-side: get from cookies
  if (typeof window === 'undefined') {
    const { cookies } = await import('next/headers');
    const cookieStore = await cookies();
    return cookieStore.get('accessToken')?.value ?? null;
  }
  
  // Client-side: get from localStorage
  return localStorage.getItem('accessToken');
};

export const sdk = createApiClient({ 
  baseUrl: process.env.NEXT_PUBLIC_API_BASE_URL! 
})
  .addPlugin(new ErrorHandlerPlugin())
  .addPlugin(new AuthenticationPlugin({ getAccessToken }));
```

### 登录流程示例

```typescript
import { sdk } from './lib/sdk/client';
import { Login } from '@deliverart/sdk-js-auth';

// Disable authentication for login request
sdk.authentication.disable();

try {
  const response = await sdk.call(new Login({
    email: 'user@example.com',
    password: 'password123'
  }));
  
  // Store the token
  localStorage.setItem('accessToken', response.token);
  
  // Re-enable authentication for subsequent requests
  sdk.authentication.enable();
  
  // Now all requests will include the Authorization header
  const user = await sdk.call(new GetCurrentUser());
  
} catch (error) {
  console.error('Login failed:', error);
}
```

### 日志流程示例

```typescript
import { sdk } from './lib/sdk/client';

// Clear the token
localStorage.removeItem('accessToken');

// Disable authentication (optional, depends on your needs)
sdk.authentication.disable();

// Redirect to login page
window.location.href = '/login';
```

### 托肯刷新示例

```typescript
import { sdk } from './lib/sdk/client';
import { AuthenticationError } from '@deliverart/sdk-js-authentication';

let tokenRefreshPromise: Promise<string> | null = null;

const getAccessToken = async (): Promise<string | null> => {
  let token = localStorage.getItem('accessToken');
  
  // Check if token is expired (you need to implement this)
  if (token && isTokenExpired(token)) {
    // Ensure only one refresh happens at a time
    if (!tokenRefreshPromise) {
      tokenRefreshPromise = refreshToken();
    }
    
    try {
      token = await tokenRefreshPromise;
      localStorage.setItem('accessToken', token);
    } finally {
      tokenRefreshPromise = null;
    }
  }
  
  return token;
};

async function refreshToken(): Promise<string> {
  const refreshToken = localStorage.getItem('refreshToken');
  
  if (!refreshToken) {
    throw new AuthenticationError('No refresh token available');
  }
  
  // Disable authentication for refresh request
  sdk.authentication.disable();
  
  try {
    const response = await sdk.call(new RefreshToken({ refreshToken }));
    sdk.authentication.enable();
    return response.accessToken;
  } catch (error) {
    // Refresh failed, redirect to login
    localStorage.clear();
    window.location.href = '/login';
    throw error;
  }
}

function isTokenExpired(token: string): boolean {
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload.exp * 1000 < Date.now();
  } catch {
    return true;
  }
}
```

### 处理错误

```typescript
import { AuthenticationError } from '@deliverart/sdk-js-authentication';

try {
  await sdk.call(new GetUser('123'));
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
    // Redirect to login page
    window.location.href = '/login';
  }
}
```

## 如何运作

该插件增加了一个请求中间软件:

1.  打电话给你 `getAccessToken` 函数以获取当前符号
2.  如果找到一个符号,请添加到 `Authorization` 页眉为 `Bearer <token>`
3.  如果找不到令牌并启用认证, 则丢出一个 `AuthenticationError`
4.  如果禁用认证, 跳过添加授权头

## 最佳做法

### 1\. 集中托肯管理

创建用于符号管理的专用模块 :

```typescript
// lib/auth/tokens.ts
export const setAccessToken = (token: string) => {
  localStorage.setItem('accessToken', token);
};

export const getAccessToken = (): string | null => {
  return localStorage.getItem('accessToken');
};

export const clearTokens = () => {
  localStorage.removeItem('accessToken');
  localStorage.removeItem('refreshToken');
};
```

### 2\. 安全托肯存储

-   使用 `httpOnly` 可能时为令牌提供饼干( 更加安全)
-   如果可能,避免在生产时将敏感标志储存在当地Storage中
-   考虑为移动应用程序使用安全存储库

### 3\. 处理托肯过期

在令牌过期前执行自动令牌刷新:

```typescript
const getAccessToken = async (): Promise<string | null> => {
  const token = localStorage.getItem('accessToken');
  
  if (token && willExpireSoon(token)) {
    return await refreshAccessToken();
  }
  
  return token;
};

function willExpireSoon(token: string, bufferSeconds = 60): boolean {
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload.exp * 1000 < Date.now() + (bufferSeconds * 1000);
  } catch {
    return true;
  }
}
```

### 4\. 全球错误处理

为认证错误设置全局错误处理 :

```typescript
import { ApiError } from '@deliverart/sdk-js-error-handler';

window.addEventListener('unhandledrejection', (event) => {
  if (event.reason instanceof ApiError && event.reason.statusCode === 401) {
    // Handle unauthorized errors globally
    clearTokens();
    window.location.href = '/login';
  }
});
```

## 许可证

麻省理工学院

## 常见问题

### @deliverart/sdk-js-authentication 是什么？

交付艺术 SDK 认证模块

### 如何安装 @deliverart/sdk-js-authentication？

在项目目录运行 npm install @deliverart/sdk-js-authentication，或使用 pnpm add / yarn add / bun add。

### @deliverart/sdk-js-authentication 支持 TypeScript 吗？

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

### @deliverart/sdk-js-authentication 支持 ESM 还是 CommonJS？

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

### @deliverart/sdk-js-authentication 可以商用吗？

@deliverart/sdk-js-authentication 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @deliverart/sdk-js-authentication 的下载量有多少？

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

### @deliverart/sdk-js-authentication 还在维护吗？

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

