# @gapi/auth 中文文档

规范地址：https://npmcn.com/package/%40gapi/auth/

版本：1\.8\.263
npm 元数据更新时间：2026-11-15T16:23:27.602Z
中文译文更新时间：2026-11-15T23:07:28.982Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40gapi/auth
原文对照：https://npmcn.com/package/%40gapi/auth/?lang=original
项目主页：https://github.com/Stradivario/gapi-auth#readme
源码仓库：https://github.com/Stradivario/gapi-auth

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

- 包体积（解压后）：15.3 kB，14 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2018-07-03T13:27:46.480Z
- 最新版本发布：2026-11-15T16:23:27.449Z
- 近 30 天下载量：4427（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：539（近 12 个月 116 个）

## 中文简介

`bash $ npm install @gapi/auth --save`

## 安装

```sh
npm install @gapi/auth
```

也可以使用：`pnpm add @gapi/auth`、`yarn add @gapi/auth`、`bun add @gapi/auth`

## README

# @ Gapi 认证模块

##### 问题/问题可写票 [这里](https://github.com/Stradivario/gapi/issues)

##### 本模块意在与 [rxdi 数据](https://github.com/rxdi/core) 或者说 [差额i](https://github.com/Stradivario/gapi)

## 安装和基本实例:

##### 要安装 Gapi 模块, 请运行 :

```bash
$ npm install @gapi/auth --save
```

## 正在拍摄 @gapi/ auth

##### 在 AppModule 或 CoreModule 内导入

```typescript
import { Module } from '@rxdi/core';
import { AuthModule } from '@gapi/auth';

@Module({
  imports: [
    AuthModule.forRoot({
      algorithm: 'HS256',
      cert: 'dadada',
      cyper: {
        algorithm: 'dada',
        iv: '',
        privateKey: 'dadada',
      },
    }),
  ],
})
export class CoreModule {}
```

##### 创建 Auth 服务并提供

```typescript
import { Service } from '@rxdi/core';
import * as Boom from 'boom';
import { AuthInterface, AuthInternalService, TokenData } from '@gapi/auth';

export interface UserInfo {
  scope: ['ADMIN', 'USER'];
  type: 'ADMIN' | 'USER';
  iat: number;
}

@Service()
export class AuthService implements AuthInterface {
  constructor(private authService: AuthInternalService) {}

  onSubOperation(message, params, webSocket) {
    return params;
  }

  onSubConnection(connectionParams): TokenData {
    if (connectionParams.token) {
      return this.validateToken(connectionParams.token, 'Subscription');
    } else {
      throw Boom.unauthorized();
    }
  }

  validateToken(
    token: string,
    requestType: 'Query' | 'Subscription' = 'Query'
  ): any {
    const user = <any>this.authService.verifyToken(token);
    user.type = user.scope[0];
    console.log(`${requestType} from: ${JSON.stringify(user)}`);
    if (user) {
      return user;
    } else {
      throw Boom.unauthorized();
    }
  }

  signJWTtoken(tokenData: TokenData): string {
    return this.authService.sign(tokenData);
  }

  issueJWTToken(tokenData: TokenData) {
    const jwtToken = this.authService.sign({
      email: '',
      id: 1,
      scope: ['ADMIN', 'USER'],
    });
    return jwtToken;
  }

  verifyToken(token: string): TokenData {
    return this.authService.verifyToken(token);
  }

  decryptPassword(password: string): string {
    return this.authService.decrypt(password);
  }

  encryptPassword(password: string): string {
    return this.authService.encrypt(password);
  }
}
```

##### 提供此特定 Auth 服务 `authentication` coreModule.forRoot 内的参数

```typescript
import { CoreModule, Module } from '@gapi/core';
import { AuthService } from './app/core/services/auth/auth.service';
import { AuthModule } from '@gapi/auth';
import { readFileSync } from 'fs';

@Module({
  imports: [
    AuthModule.forRoot({
      algorithm: 'HS256',
      cert: readFileSync('./cert.key'),
      cyper: {
        algorithm: 'aes256',
        iv: 'Jkyt1H3FA8JK9L3B',
        privateKey: '8zTVzr3p53VC12jHV54rIYu2545x47lA',
      },
    }),
    CoreModule.forRoot({
      pubsub: {
        authentication: AuthService,
      },
      graphql: {
        authentication: AuthService,
      },
    }),
  ],
})
export class FrameworkImports {}
```

然后通过单一认证方法确保订阅、变异和查询的安全 `validateToken` 内部 `AuthService`来啊!

TODO: 更好的文档...

享受吧! (笑声)

## 常见问题

### @gapi/auth 是什么？

bash $ npm install @gapi/auth --save

### 如何安装 @gapi/auth？

在项目目录运行 npm install @gapi/auth，或使用 pnpm add / yarn add / bun add。

### @gapi/auth 支持 TypeScript 吗？

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

### @gapi/auth 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @gapi/auth 可以商用吗？

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

### @gapi/auth 的下载量有多少？

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

### @gapi/auth 还在维护吗？

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

