# @5stones/nest-oidc 中文文档

规范地址：https://npmcn.com/package/%405stones/nest-oidc/

版本：2\.2\.1
npm 元数据更新时间：2026-06-09T19:02:09.756Z
中文译文更新时间：2026-11-05T21:46:37.468Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%405stones/nest-oidc
原文对照：https://npmcn.com/package/%405stones/nest-oidc/?lang=original
项目主页：https://github.com/5-stones/nest-oidc#readme

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

- 包体积（解压后）：192 kB，92 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- peer 依赖：@apollo/gateway \*，@nestjs/axios ^1\.0\.0 \|\| ^2\.0\.0 \|\| ^3\.0\.0 \|\| ^4\.0\.0，@nestjs/common ^9\.0\.0 \|\| ^10\.0\.0 \|\| ^11\.0\.0，@nestjs/core ^9\.0\.0 \|\| ^10\.0\.0 \|\| ^11\.0\.0，@nestjs/graphql \*，@nestjs/jwt \*，@nestjs/passport \*，passport \*，passport-jwt \*，reflect-metadata \*
- 首次发布：2021-06-03T17:35:15.257Z
- 最新版本发布：2026-06-09T19:02:09.571Z
- 近 30 天下载量：16330（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：15（近 12 个月 2 个）

## 中文简介

NestJS API 的 OIDC 认证模块

## 安装

```sh
npm install @5stones/nest-oidc
```

也可以使用：`pnpm add @5stones/nest-oidc`、`yarn add @5stones/nest-oidc`、`bun add @5stones/nest-oidc`

## README

# 雀巢JS OIDC

用于 NestJS 和 GraphQL 或 REST 的可配置 OIDC 库 .

-   [安装](https://npmcn.com/package/%405stones/nest-oidc/#readme-install)
-   [基本设置和使用](https://npmcn.com/package/%405stones/nest-oidc/#readme-basic-setup--usage)
-   [警卫](https://npmcn.com/package/%405stones/nest-oidc/#readme-guards)
    -   [资源](https://npmcn.com/package/%405stones/nest-oidc/#readme-rest-guard)
    -   [图QL](https://npmcn.com/package/%405stones/nest-oidc/#readme-graphql-guard)
-   [当前用户](https://npmcn.com/package/%405stones/nest-oidc/#readme-current-user)
    -   [资源](https://npmcn.com/package/%405stones/nest-oidc/#readme-rest-user)
    -   [图QL](https://npmcn.com/package/%405stones/nest-oidc/#readme-graphql-user)
-   [作用](https://npmcn.com/package/%405stones/nest-oidc/#readme-roles)
-   [角色评价员](https://npmcn.com/package/%405stones/nest-oidc/#readme-role-evaluators)
-   [JWT 绘图](https://npmcn.com/package/%405stones/nest-oidc/#readme-jwt-mapping)
-   [高级](https://npmcn.com/package/%405stones/nest-oidc/#readme-advanced)
    -   [正在认证图QL 订阅](https://npmcn.com/package/%405stones/nest-oidc/#readme-authenticating-graphql-subscriptions)
    -   [可选认证](https://npmcn.com/package/%405stones/nest-oidc/#readme-optional-authentication)
-   [释放](https://npmcn.com/package/%405stones/nest-oidc/#readme-release)

## 安装

安装 `nest-oidc`数字 :

```sh
npm i @5stones/nest-oidc
```

安装它的对等依赖 :

```sh
npm i @nestjs/jwt @nestjs/passport passport passport-jwt
```

:警告:注意:如果在GraphQL中使用此软件包,则需要 安装相应的 GQL 库. [请先跟随NestJS文件.](https://docs.nestjs.com/graphql/quick-start)

## 基本设置和使用

您需要导入并配置 `AuthModule` 在您的申请。 这个 软件包中包含一个JWT认证策略,将验证JWT对 发行人的公用钥匙。 您必须通过配置值 `oidcAuthority`。 。 。 .

```ts
import { Module } from '@nestjs/common';
import { AuthModule } from '@5stones/nest-oidc';

@Module({
  imports: [
    ...
    AuthModule.forRoot({
      oidcAuthority: 'http://iam.app.com/auth/realms/app',
    }),
  ],
})
export class AppModule {}
```

这将增加JWT的验证战略,并将核查任何收到的JWT的 反国际开发部当局的公用钥匙.

最后,你应该 装饰你的终点 与提供警卫.

## 警卫

这个软件包输出两个基本守卫:

-   `JwtAuthGuard` - 在REST背景下使用.
-   `JwtAuthGuardGraphQL` - 用于GQL环境.

#### 警卫

应用后卫需要通过有效的JWT才能进入任何 控制器端点:

```ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { Roles, JwtAuthGuard } from '@5stones/nest-oidc';

@UseGuards(JwtAuthGuard)
@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}
```

您也可以在特定终点上使用:

```ts
import { Controller, Get, Post, UseGuards } from '@nestjs/common';
import { Roles, JwtAuthGuard } from '@5stones/nest-oidc';

@Controller('cats')
export class CatsController {
  @UseGuards(JwtAuthGuard)
  @Post()
  create(): string {
    return 'This action adds a new cat';
  }

  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}
```

#### 图QL 守护

应用后卫需要通过有效的JWT才能进入任何 控制器端点:

```ts
import { UseGuards } from '@nestjs/common';
import { Resolver } from '@nestjs/graphql';
import { JwtAuthGuardGraphQL } from '@5stones/nest-oidc';

@UseGuards(JwtAuthGuardGraphQL)
@Resolver(() => Cat)
export class CatResolver {
  ...
}
```

您也可以在特定终点上使用:

```ts
import { UseGuards } from '@nestjs/common';
import { Resolver, Query, Mutation } from '@nestjs/graphql';
import { JwtAuthGuardGraphQL } from '@5stones/nest-oidc';

@Resolver(() => Cat)
export class CatResolver {

  @Query(() => [Cat], { name: 'allCats' })
  async findAll() {
    ...
  }

  @UseGuards(JwtAuthGuardGraphQL)
  @Mutation(() => Cat, { name: 'createCat' })
  async create() {
    ...
  }
}
```

## 当前用户

此套件输出两个基本的用户装饰器:

-   `CurrentUser` - 在REST背景下使用.
-   `CurrentUserGraphQL` - 用于GQL环境.

#### REST 用户

```ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { Roles, JwtAuthGuard, CurrentUser } from '@5stones/nest-oidc';

@UseGuards(JwtAuthGuard)
@Controller('cats')
export class CatsController {
  @Get()
  findAll(@CurrentUser() user: any): string {
    return 'This action returns all cats';
  }
}
```

#### 图QL 用户

```ts
import { UseGuards } from '@nestjs/common';
import { Resolver, Query } from '@nestjs/graphql';
import { JwtAuthGuardGraphQL, CurrentUserGraphQL } from '@5stones/nest-oidc';

@UseGuards(JwtAuthGuardGraphQL)
@Resolver(() => Cat)
export class CatResolver {

  @Query(() => [Cat], { name: 'allCats' })
  async findAll(@CurrentUserGraphQL() user: any) {
    ...
  }
}
```

## 作用

如果您想要根据 JWT 的属性允许不同的端点, 请 可以使用 `Roles` 与Auth Guards(两者)一起装饰 (原始内容存档于2018-10-21). REST & GQL. 这个 `Roles` 装饰者将接受一个列表 `string`和意愿 检查用户访问端点时是否在 `user.roles` 属性。 它期望着 `user.roles` 属性为平面数组 弦乐.

#### 示例

```ts
import { UseGuards } from '@nestjs/common';
import { Resolver, Query, Mutation, Args, ID } from '@nestjs/graphql';
import { JwtAuthGuardGraphQL, Roles } from '@5stones/nest-oidc';

@UseGuards(JwtAuthGuardGraphQL)
@Resolver(() => Cat)
export class CatResolver {

  @Query(() => [Cat], { name: 'allCats' })
  async findAll(): Promise<Cat[]> {
    ...
  }

  @Roles()
  @Query(() => Cat, { name: 'Cat' })
  async findOne(@Args('id', { type: () => ID }) id: number): Promise<Cat> {
    ...
  }

  @Roles('ADMIN', 'SUPER_ADMIN')
  @Mutation(() => Cat, { name: 'createCat' })
  async create(): Promise<Cat> {
    ...
  }
}
```

在这种假想中,变异只能被一个 `ADMIN` 或者说 `SUPER_ADMIN` 但查询可以由任何使用有效JWT的用户执行.

:警告:注意:如果你没有通过 _任意_ 角色参数 `Roles` 装饰(即. `@Roles()`这与完全不添加装饰者是一样的. 这就是说,任何情景 以上 `findAll` 编辑 `findOne` 查询 行为相同.

## 角色评价员

如果你的JWT没有在本地拥有 `.roles` 字符串的属性,你可以 使用评估人员将JWT的属性映射到角色. 你可以这么做 配置 `roleEvaluators`。 。 。 . `roleEvaluators` 是数组 `RoleEvaluator` 由下列物体组成的物体: `expression`,以及访问 `role` 该特定表达式在评估时给予 `true`。 。 。 .

一个 `expression` 可以是任何有效的 [`jexl`](https://www.npmjs.com/package/jexl) 表达式.

#### 示例

假设您有一个JWT,其结构如下:

```ts
{
  roles: [
     { name: "SUPER_USER", id: 1 },
     ...
     { name: "PREMIUM", id: 2 },
  ],
}
```

然后您可以配置一个像下面这样的评估者, 它将映射一个 用户 `role` 名称 `SUPER_USER` 页:1 `ADMIN` 在应用程序中的角色.

```ts
import { Module } from '@nestjs/common';
import { AuthModule } from '@5stones/nest-oidc';

@Module({
  imports: [
    ...
    AuthModule.forRoot({
      oidcAuthority: 'http://iam.app.com/auth/realms/app',
      roleEvaluators: [
        {
          expression: 'jwt.roles[.name == "SUPER_USER"]|length > 0',
          role: 'ADMIN',
        },
      ],
    }),
  ],
})
export class AppModule {}
```

应用程序中的用户对象现在有以下内容:

```ts
{
  ...
  roles: [
    "ADMIN",
  ],
}
```

然后,你只是 装饰你的终点 `@Roles('ADMIN')` 为锁定该角色的用户而作注释.

## JWT 绘图器

默认情况下,JWT有效载荷作为用户传入应用程序. 不过, 如果您需要将 JWT 有效载荷映射到不同的结构中, 您可以通过 `jwtMapper` 选项 :

```ts
import { Module } from '@nestjs/common';
import { AuthModule } from '@5stones/nest-oidc';

@Module({
  imports: [
    ...
    AuthModule.forRoot({
      oidcAuthority: 'http://iam.app.com/auth/realms/app',
      jwtMapper: async (payload: any) => ({
        id: payload.sub,
        email: payload.email,
        ...
      }),
    }),
  ],
})
export class AppModule {}
```

## 高级

#### 正在认证图QL 订阅

Websocket spec 不支持信头, 所以如果您想要认证 a GraphQL 通过标准 Guard & 角色装饰器订阅, 您可以这样做, 但是 你需要修改你的 `GraphQLModule` 配置 。 以下例子将 教你如何用这个 `graphql-ws` 图书馆.

第一步是确保您通过 Auth 令牌作为参数 通过您的网络保护请求. [更多信息 `graphql-ws` 文档](https://github.com/enisdenjo/graphql-ws#user-content-apollo-client)

接下来你需要修改 `GraphQLModule`是因为 `onConnect` 财务报告和审定财务报表 `context` 函数来映射符号和请求。 你个 [可以读取 NestJS 文档](https://docs.nestjs.com/graphql/subscriptions#authentication-over-websocket) 通常如何做到这一点,但文件仅涉及审定 直接在 `onConnect` 函数。 然而,允许 由卫兵完成,您需要将符号映射到请求对象上的信头中 然后确保你总是返回 请求由处理 `JwtStrategy`。见以下例子:

```ts
// app.module.ts
...
import type { Context } from 'graphql-ws';

...
@Module({
  imports: [
    GraphQLModule.forRoot({
      ...
      subscriptions: {
        'graphql-ws': {
          onConnect: (context: Context<any>) => {
            const { connectionParams, extra } = context;
            const authToken = connectionParams?.Authorization;

            if (authToken) {
              // Add the auth token to the request object provided by `graphql-ws`
              // NOTE: headers are lowercased in express. Using `Authorization`
              // will result in a failure to authenticate.
              extra.request.headers.authorization = authToken;
            }
          },
        }
      },
      context: (context) => {
        if (context?.req === undefined) {
          // The jwt strategy requires a request with headers to perform jwt
          // validation. If no request exists in the context object then we're
          // dealing with a websocket connection. In that case pass along the
          // request object provided by the `graphql-ws` context for validation.
          context.req = context.extra.request;
        }

        // return the context object.
        return context;
      },
    }),
    ...
  ],
})
export class AppModule implements NestModule {
  ...
}
```

配置完成后,您就可以应用 `JwtAuthGuardGraphQL` 财务报告和审定财务报表 `Roles` 任何其它解析器、查询或变异的装饰器.

#### 可选认证

你可以用这个 `IsAuthenticationOptional` 端点或解析器上的装饰器 与一个认证警卫。 如果这样做了,那么JWTs将大量出现 `user` 对象。 如果一个无效的JWT通过,或者没有通过JWT 全部,那么请求时不会有用户.

## 释放

此工程的标准放出命令为:

```
npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease | from-git]
```

此命令将 :

1.  生成/更新 Changelog
2.  弹出软件包版本
3.  标记推动承诺( P)

譬如说.

```
npm version 1.2.17
npm version patch // 1.2.17 -> 1.2.18
```

## 常见问题

### @5stones/nest-oidc 是什么？

NestJS API 的 OIDC 认证模块

### 如何安装 @5stones/nest-oidc？

在项目目录运行 npm install @5stones/nest-oidc，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@nestjs/axios（^1\.0\.0 \|\| ^2\.0\.0 \|\| ^3\.0\.0 \|\| ^4\.0\.0）、@nestjs/common（^9\.0\.0 \|\| ^10\.0\.0 \|\| ^11\.0\.0）、@nestjs/core（^9\.0\.0 \|\| ^10\.0\.0 \|\| ^11\.0\.0）、@nestjs/jwt（\*）、@nestjs/passport（\*）、passport（\*）、passport-jwt（\*）、reflect-metadata（\*）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @5stones/nest-oidc 支持 TypeScript 吗？

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

### @5stones/nest-oidc 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @5stones/nest-oidc 可以商用吗？

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

### @5stones/nest-oidc 的下载量有多少？

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

### @5stones/nest-oidc 还在维护吗？

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

