# @blimmer/cdk-github-oidc 中文文档

规范地址：https://npmcn.com/package/%40blimmer/cdk-github-oidc/

版本：1\.2\.0
npm 元数据更新时间：2026-07-28T09:24:27.959Z
中文译文更新时间：2026-11-08T06:49:18.639Z
软件包许可：Apache-2\.0

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

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

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

- 包体积（解压后）：360 kB，33 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：aws-cdk-lib ^2\.73\.0，constructs ^10\.5\.1
- 首次发布：2025-01-24T01:17:31.185Z
- 最新版本发布：2026-07-28T09:24:27.633Z
- 近 30 天下载量：2819（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：5（近 12 个月 1 个）

## 中文简介

为 CircleCI 工作创建 OIDC 角色的 AWS CDK 构造

## 安装

```sh
npm install @blimmer/cdk-github-oidc
```

也可以使用：`pnpm add @blimmer/cdk-github-oidc`、`yarn add @blimmer/cdk-github-oidc`、`bun add @blimmer/cdk-github-oidc`

## README

# `@blimmer/cdk-github-oidc`

一个 CDK 构建库,可以使用 OpenID Connection(OIDC) 在 GitHub Actions 和 AWS 之间安全认证. 这就不再需要在您的 GitHub 寄存器中长期使用 AWS 证书 .

## 什么是OIDC吗?

OIDC( OpenID Connect) 允许 GitHub 动作使用短寿命的符号直接认证 AWS 而不是 存储 AWS 证书 。 这一过程在下文中作了描述 [GitHub 文档](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/about-security-hardening-with-openid-connect)。 。 。 .

为什么使用OIDC而不是访问密钥?

-   消除将 AWS 证书作为 GitHub 机密存储的必要性
-   提供寿命短、自动旋转的证书
-   基于寄存器、分支、环境或其他条件启用精细的访问控制
-   采用安全最佳做法获取云

## 安装

### 节点.js

```shell
npm install --save @blimmer/cdk-github-oidc
```

或者说

```shell
yarn add @blimmer/cdk-github-oidc
```

### 蟒

```bash
pip install cdk-github-oidc
```

## 使用量

下面的例子为TypeScript. 关于每种支持语言的完整API,请参见 [API.md (英语)](https://npmcn.com/API.md)。 。 。 .

### 创建或导入提供者

每个AWS账户都必须由单一的OIDC提供商来固定.

要在您的堆栈中创建,请使用 `GithubActionsIdentityProvider` 构造.

```ts
import { GithubActionsIdentityProvider } from "@blimmer/cdk-github-oidc";

export class MyStack extends Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    const provider = new GithubActionsIdentityProvider(this, "Provider");
  }
}
```

或者,如果另一个堆栈创建了提供者,你可以使用 `GithubActionsIdentityProvider.fromAccount()` 方法.

```ts
import { GithubActionsIdentityProvider } from "@blimmer/cdk-github-oidc";

export class MyStack extends Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    const provider = GithubActionsIdentityProvider.fromAccount(this);
  }
}
```

### 创建角色

一旦向提供者拥有了手柄,就可以创建由GitHub Actions承担的角色. 您给予此角色权限 访问资源/ AP 您需要( 更多信息) [下级](https://npmcn.com/package/%40blimmer/cdk-github-oidc/#readme-granting-permissions-to-the-role)) (中文(简体) ).

```ts
import { GithubActionsRole, GithubActionsIdentityProvider, BranchFilter } from "@blimmer/cdk-github-oidc";

export class MyStack extends Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    const provider = new GithubActionsIdentityProvider(this, "Provider");

    const role = new GithubActionsRole(this, "Role", {
      provider,
      roleName: "my-github-actions-role",
      description: "Role assumed by GitHub Actions",
      subjectFilters: [
        new BranchFilter({
          owner: "blimmer",
          ownerId: "630449",
          repository: "cdk-github-oidc",
          repositoryId: "919628491",
          branch: "*",
        }),
      ],
    });
  }
}
```

`ownerId` 财务报告和审定财务报表 `repositoryId` 选择使用 GitHub [a. 不可改变的主题索赔](https://npmcn.com/package/%40blimmer/cdk-github-oidc/#readme-immutable-subject-claims),默认值为 2026年7月15日之后创建的寄存器. 如果你的寄存器早于此,就同时关闭.

### 主题过滤器

你必须经过一个或一个以上 `SubjectFilter`页:1 `GithubActionsRole` 构造。 这些过滤器用于确定 gitHub 动作工作流程可以承担该角色.

此构造会曝光以下过滤器的一等支持. 实例省略 `ownerId` 财务报告和审定财务报表 `repositoryId` 改为 将焦点放在每个过滤器的操作上;如果您的存储器使用不可改变的主题要求,则如上所示添加.

-   [`AllowAllFilter`](https://npmcn.com/API.md#allowallfilter)
    
    ```ts
    // Allow all branches, tags, environments, pull requests, etc.
    new AllowAllFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
    });
    ```
    
-   [`BranchFilter`](https://npmcn.com/API.md#branchfilter)
    
    ```ts
    // Allow all branches
    new BranchFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
      branch: "*",
    });
    
    // Specify a branch
    new BranchFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
      branch: "main",
    });
    
    // Specify a branch pattern
    new BranchFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
      branch: "feature/*",
    });
    ```
    
-   [`TagFilter`](https://npmcn.com/API.md#tagfilter)
    
    ```ts
    // Allow all tags
    new TagFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
      tag: "*",
    });
    
    // Specify a tag
    new TagFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
      tag: "v1.0.0",
    });
    
    // Specify a tag pattern
    new TagFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
      tag: "v1.*",
    });
    ```
    
-   [`EnvironmentFilter`](https://npmcn.com/API.md#environmentfilter)
    
    ```ts
    // Allow all environments
    new EnvironmentFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
      environment: "*",
    });
    
    // Specify an environment
    new EnvironmentFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
      environment: "staging",
    });
    ```
    
-   [`PullRequestFilter`](https://npmcn.com/API.md#pullrequestfilter)
    
    ```ts
    // Allow all pull requests
    new PullRequestFilter({
      owner: "blimmer",
      repository: "cdk-github-oidc",
    });
    ```
    

如果这些过滤器都不符合您的使用大小写, 您可以通过 [`IGithubActionOidcFilter`](https://npmcn.com/API.md#igithubactionoidcfilter) 接口,或使用 [`CustomFilter`](https://npmcn.com/API.md#customfilter) 构造.

在写自己的作品时, 从受保护对象中构建主题 `repositoryClaim` 比从 `owner` 财务报告和审定财务报表 `repository` 直接说 随你怎么说 `repo:` 前缀过滤器被配置,所以您的过滤器继续工作 如果寄存器移动到 [a. 不可改变的主题索赔](https://npmcn.com/package/%40blimmer/cdk-github-oidc/#readme-immutable-subject-claims)。 。 。 .

```ts
class DeploymentFilter extends IGithubActionOidcFilter {
  public toSubject(): string {
    return `${this.repositoryClaim}:deployment`;
  }
}
```

您可以在 [Github 文档](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/about-security-hardening-with-openid-connect#configuring-the-subject-in-your-cloud-provider)

### B. 无法更改的主题索赔

GitHub 移动到一个 [c. 不可改变的主题索赔格式](https://docs.github.com/en/actions/reference/security/oidc#immutable-subject-claims) 嵌入数字所有者和寄存器ID:

```
repo:blimmer/cdk-github-oidc:ref:refs/heads/main                   # previous
repo:blimmer@630449/cdk-github-oidc@919628491:ref:refs/heads/main  # immutable
```

2026年7月15日之后创建的仓库使用不可改变的格式,在此之后重新命名或转移的仓库也是如此 约会。 在 OIDC 设置 UI 或 NOG 中,所有其它文件都保留上一个格式,直到您选择使用 [(原始内容存档于2013-10-12) (英语). REST API](https://docs.github.com/en/rest/actions/oidc)。一个寄存器会发出一种或另一种格式,永远不会同时发出两种格式.

过 `ownerId` 财务报告和审定财务报表 `repositoryId` 到任何获取永久格式的过滤器 :

```ts
new BranchFilter({
  owner: "blimmer",
  ownerId: "630449",
  repository: "cdk-github-oidc",
  repositoryId: "919628491",
  branch: "main",
});
```

离开他们,你得到之前的格式,这就是什么 [主题过滤器](https://npmcn.com/package/%40blimmer/cdk-github-oidc/#readme-subject-filters) 上面的例子.

#### 找到身份证

```sh
gh api repos/OWNER/REPO --jq '{ownerId: .owner.id, repositoryId: .id}'
```

要检查寄存器的当前格式, 请读 `sub_claim_prefix`数字 :

```sh
gh api repos/OWNER/REPO/actions/oidc/customization/sub
# {"use_default":true,"use_immutable_subject":false,"sub_claim_prefix":"repo:blimmer/cdk-github-oidc"}
```

同样的环境生活 `https://github.com/OWNER/REPO/settings/actions/oidc-configuration`。 。 。 .

#### 快速迁移

如果你有不止几个过滤器 把这个交给你的编码代理.

显示提示

```text
Upgrade `@blimmer/cdk-github-oidc` to the latest version, then audit this CDK app for GitHub's immutable OIDC
subject claim format.

Background: GitHub embeds numeric owner and repository IDs in the OIDC `sub` claim
(`repo:owner@123/repo@456:ref:refs/heads/main` instead of `repo:owner/repo:ref:refs/heads/main`). Repositories
created, renamed, or transferred after July 15, 2026 use it automatically. Older repositories keep the previous
format until someone opts in. A repository emits one format or the other, never both, so a trust policy built for
the wrong format fails with `Not authorized to perform sts:AssumeRoleWithWebIdentity`.

For every subject filter passed to a `GithubActionsRole` in this app:

1. Run `gh api repos/<owner>/<repository>/actions/oidc/customization/sub` and read `use_immutable_subject`.
2. If it is `false`, leave the filter alone. It is already correct.
3. If it is `true`, run `gh api repos/<owner>/<repository> --jq '{ownerId: .owner.id, repositoryId: .id}'` and add
   both values to that filter as `ownerId` and `repositoryId` (strings, not numbers). Keep `owner` and
   `repository` as the plain names.

Then find every class in this app that extends `IGithubActionOidcFilter`. If its `toSubject()` builds the subject
from `this.owner` and `this.repository`, rewrite it to use the `this.repositoryClaim` getter instead, leaving the
rest of the subject unchanged. Custom filters that skip this keep emitting the previous format no matter which IDs
are passed to them.

Report any repository the `gh` calls fail for rather than guessing its IDs, since a wrong ID produces a role nobody
can assume. Do not add, remove, or re-scope any filter, and do not change anything beyond the filter arguments and
the custom filter subject construction.
```

#### 切换现有仓库

添加第二个带ID的过滤器,部署,选择在GitHub上,然后删除原来的过滤器. 这个角色都相信 中间的主体,所以没有突破中关节.

```ts
subjectFilters: [
  new BranchFilter({ owner: "blimmer", repository: "cdk-github-oidc", branch: "main" }),
  new BranchFilter({
    owner: "blimmer",
    ownerId: "630449",
    repository: "cdk-github-oidc",
    repositoryId: "919628491",
    branch: "main",
  }),
];
```

双重检查身份证 一个错误的产生一个 永远不匹配的主题, 唯一的症状是 `Not authorized to perform sts:AssumeRoleWithWebIdentity`。 。 。 .

别拿通配符 `blimmer@*` 避免寻找他们。 相信每个账户的名字 `blimmer`, (中文(简体) ), 包括当当前所有者重取名称或删除名称时声称名称的人。 确切的防止,这就是为什么身份证 已存在.

### 授予角色权限

这个 `GithubActionsRole` 构造 _是一个_ `Role` 构造,这样您就可以使用与您相同的所有属性和方法 {\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}会是正常的 [光盘IAM `Role` 构造](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html)。 。 。 .

```ts
import { GithubActionsRole, GithubActionsIdentityProvider, BranchFilter } from "@blimmer/cdk-github-oidc";
import { Bucket } from "aws-cdk-lib/aws-s3";
import { PolicyStatement } from "aws-cdk-lib/aws-iam";

export class MyStack extends Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    const bucket = new Bucket(this, "Bucket");

    const provider = new GithubActionsIdentityProvider(this, "Provider");
    const role = new GithubActionsRole(this, "Role", {
      provider,
      roleName: "my-github-actions-role",
      description: "Role assumed by GitHub Actions",
      subjectFilters: [
        new BranchFilter({
          owner: "blimmer",
          repository: "cdk-github-oidc",
          branch: "*",
        }),
      ],
    });

    // Grant access via CDK `grant*` methods
    // https://docs.aws.amazon.com/cdk/v2/guide/permissions.html#permissions_grants
    role.grantReadWrite(bucket);

    // Add a custom policy
    role.addToPolicy(
      new PolicyStatement({
        actions: ["s3:PutObject"],
        resources: ["arn:aws:s3:::my-bucket/*"],
      }),
    );
  }
}
```

### 在工作流程中发挥作用

要使用 GitHub 动作工作流程中的角色, 您可以使用 `aws-actions/configure-aws-credentials` 行动.

```yaml
jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write # Required for OIDC role assumption
    steps:
      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/my-github-actions-role
          region: us-west-2
```

见 [页:1 `aws-actions/configure-aws-credentials` 文档](https://github.com/aws-actions/configure-aws-credentials) 页:1 更多细节.

## 解决问题

### 共同问题

1.  **角色假设失败**: 确保您的 GitHub 动作具有所需的权限 :
    
    ```yaml
    permissions:
      id-token: write # Required for OIDC
      contents: read # Required for checking out code
    ```
    
2.  **提供者已经存在**:每个AWS账户只有一个OIDC供应商可以存在. 使用 `GithubActionsIdentityProvider.fromAccount()` 如果一个已经存在.
    
3.  **主体过滤器不匹配**: 双向检查您的主题过滤器配置符合您的 GitHub 工作流程上下文 . 使用日志调试提供的实际主题字符串 .
    
4.  **创建、重新命名或转让后角色假设中断**: 仓库可能已切换到 [a. 不可改变的主题索赔](https://npmcn.com/package/%40blimmer/cdk-github-oidc/#readme-immutable-subject-claims)运行 `gh api repos/OWNER/REPO/actions/oidc/customization/sub` 以查看其发射和通过的格式 `ownerId` 财务报告和审定财务报表 `repositoryId` 到过滤器,如果 `use_immutable_subject` 实值 `true`. CloudTrail)展示了实际呈现的主题.
    

## 从 `aws-cdk-github-oidc`

这个软件包灵感来自 [`aws-cdk-github-oidc`](https://github.com/aripalo/aws-cdk-github-oidc)软件包 变得无法保存.

为了这个角色 `aws-cdk-github-oidc`数字 :

```ts
import { GithubActionsIdentityProvider, GithubActionsRole } from "aws-cdk-github-oidc";

const provider = new GithubActionsIdentityProvider(scope, "GithubProvider");
const deployRole = new GithubActionsRole(scope, "DeployRole", {
  provider,
  owner: "octo-org",
  repo: "octo-repo",
  roleName: "MyDeployRole",
  description: "This role deploys stuff to AWS",
  maxSessionDuration: cdk.Duration.hours(2),
});
```

本套件中的等同角色看起来是这样的:

```ts
import { GithubActionsIdentityProvider, GithubActionsRole, AllowAllFilter } from "@blimmer/cdk-github-oidc";

const provider = new GithubActionsIdentityProvider(scope, "GithubProvider");
const deployRole = new GithubActionsRole(scope, "DeployRole", {
  provider,
  roleName: "MyDeployRole",
  description: "This role deploys stuff to AWS",
  subjectFilters: [
    // I encourage you to scope this down to a different filter (e.g., BranchFilter, TagFilter, PullRequestFilter, etc.)
    new AllowAllFilter({ owner: "octo-org", repository: "octo-repo" }),
  ],
  maxSessionDuration: cdk.Duration.hours(2),
});
```

### 资源更换

默认情况下,CloudFormation将会在摧毁旧的之前创造资源. 这是过渡时的问题 介于 `aws-cdk-github-oidc` 财务报告和审定财务报表 `@blimmer/cdk-github-oidc` 因为 `GithubActionsIdentityProvider` 是一个单子. 如果你指定一个 `roleName`。 。 。 .

要围绕这个问题开展工作,在迁移到使用这个包之前,删除旧的提供者和角色. 注意,这将 使角色在重建时无法使用几分钟

## 资源

-   [安全加强你的部署](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments) 在Github Docs号上.
-   [承担角色 `aws-actions/configure-aws-credentials`](https://github.com/aws-actions/configure-aws-credentials#assuming-a-role)

## 捐款

欢迎贡献、问题和反馈!

## 常见问题

### @blimmer/cdk-github-oidc 是什么？

为 CircleCI 工作创建 OIDC 角色的 AWS CDK 构造

### 如何安装 @blimmer/cdk-github-oidc？

在项目目录运行 npm install @blimmer/cdk-github-oidc，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：aws-cdk-lib（^2\.73\.0）、constructs（^10\.5\.1）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @blimmer/cdk-github-oidc 支持 TypeScript 吗？

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

### @blimmer/cdk-github-oidc 支持 ESM 还是 CommonJS？

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

### @blimmer/cdk-github-oidc 可以商用吗？

@blimmer/cdk-github-oidc 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @blimmer/cdk-github-oidc 的下载量有多少？

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

### @blimmer/cdk-github-oidc 还在维护吗？

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

