@aws-blocks/auth-common

中文文档
0.3.0发布于 2026/11/02Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 6.7万

AWS Blocks Auth Building Blocks的所有共享接口和UI组件. 使用此软件包来构建提供者- 不可知的 Author UI, 或者在创建自定义 Author Building Block 时导入类型 .

中文使用文档
文档目录17 节
  1. 出口
  2. 会话- cookie 安全政策 /cookies (中文(简体) )
  3. 服务器- 服务器接口( S) BlocksAuth (中文(简体) )
  4. 认证器组件
  5. 账户菜单栏
  6. 已认证
  7. 未认证用户的退后
  8. 状态
  9. Auth 状态更改订阅
  10. 广播认证更改
  11. broadcastAuthChange (低级原始)
  12. 赛明会 injectTheme + 键 --bb-* 符号)
  13. 类型
  14. AuthState
  15. AuthAction
  16. AuthField
  17. AuthUser

@aws- blocks/ auth- common (英语)

AWS Blocks Auth Building Blocks的所有共享接口和UI组件. 使用此软件包来构建提供者- 不可知的 Author UI, 或者在创建自定义 Author Building Block 时导入类型 .

设计与模拟等价细节 : 设计

出口

导出路径它提供的东西
@aws-blocks/auth-common类型 : BlocksAuth, (中文(简体) ), AuthUser, (中文(简体) ), AuthState, (中文(简体) ), AuthAction, (中文(简体) ), AuthField
@aws-blocks/auth-common/ui组件 : AccountMenuBar, (中文(简体) ), Authenticator, (中文(简体) ), AuthenticatedContent, (中文(简体) ), StatusMessage, (中文(简体) ), onAuthChange, (中文(简体) ), broadcastAuthChange, (中文(简体) ), submitAuthAction; 主题: injectTheme, (中文(简体) ), THEME_CSS, (中文(简体) ), THEME_STYLE_ID
@aws-blocks/auth-common/theme设计托盘层 : injectTheme, (中文(简体) ), THEME_CSS, (中文(简体) ), THEME_STYLE_ID
@aws-blocks/auth-common/cookies共享会话- cookie 安全政策 : resolveCookieSecurity, (中文(简体) ), buildCookieSecurityAttrs, (中文(简体) ), isLoopbackRequest, (中文(简体) ), isInsecurePublicOrigin

所有 AWS 块 Auth BBs 路由它们的会话- cookie SameSite 编号 : Secure 编号 : Partitioned 通过这个帮助者来选择,所以它们会从结构上而不是从漂移中汇合. 鉴于 { crossDomain, isLocalhost } 它返回犬科属性 :

crossDomainisLocalhost属性
false (默认)falseSameSite=Lax; Secure
falsetrueSameSite=Lax
truefalseSameSite=None; Secure; Partitioned
truetrueSameSite=None; Secure

buildCookieSecurityAttrs(input) 返回集合的 BB 的字符串窗体 Set-Cookie 手持; resolveCookieSecurity(input) 返回通过结构化饼干配置的 BB 属性对象. isLoopbackRequest(ctx) 检测回路源( r)localhost, (中文(简体) ), 127.0.0.1, (中文(简体) ), [::1](按要求) isLocalhost 决定.

可选 plainHttpOrigin 输入标记一个已部署的正门服务于平原 HTTP( 无证书的 ALB): 它会下降 Secure 来自同一来源的 Lax 饼干,否则浏览器会在HTTP上丢弃. 它并不改变跨域饼干,这是API自己的HTTPS响应设定. isInsecurePublicOrigin() 是从门的计谋中得来的BLOCKS_PUBLIC_ORIGIN 从开始 http://),从请求头里从没有. 现在 bb-auth-basic 通过它; 其它授权 BBs 保存 Secure所以在普通HTTP门后 他们的会话不会持续.

服务器- 服务器接口( S)BlocksAuth(中文(简体) )

执行所有授权基准 BlocksAuth。服务器侧码是相同的,无论提供者是谁:

import { AuthBasic } from '@aws-blocks/bb-auth-basic';

const auth = new AuthBasic(scope, 'auth');

export const api = new ApiNamespace(scope, 'api', (context) => ({
  // Require auth — throws 401 if not signed in
  async getProfile() {
    const user = await auth.requireAuth(context);
    return { username: user.username };
  },

  // Optional auth — returns null if not signed in
  async getContent() {
    const user = await auth.getCurrentUser(context);
    return user ? `Hello ${user.username}` : 'Hello guest';
  },

  // Boolean check — for branching
  async isLoggedIn() {
    return await auth.checkAuth(context);
  },
}));

// Export the state machine API for the Authenticator component
export const authApi = auth.createApi();
方法回返何时使用
requireAuth(context)Promise<AuthUser>保护终点. 投出401,如果不签入.
checkAuth(context)Promise<boolean>分支逻辑.
getCurrentUser(context)Promise<AuthUser | null>可选个性化.

认证器组件

这个 Authenticator 使UI被国家机器驱动。 它与任何认证提供者合作—— AuthBasic, (中文(简体) ), AuthOIDC, (中文(简体) ), AuthCognito 因为它基于 AuthState的逻辑.

import { Authenticator } from '@aws-blocks/auth-common/ui';
import { authApi } from 'aws-blocks';

document.body.appendChild(Authenticator(authApi));

重新样式、重新贴上标签、隐藏或完全替换制成的表格,参见 自定义 Auth 用户界面。 。 。 .

本构成部分:

  • 电话 getAuthState() 挂起,以确定要制作什么
  • 渲染器为每个可用的动作组成字段并提交按钮
  • 内部行动(否) url: 收集输入和呼叫 setAuthState({ action, ...fields })
  • 外部行动 url: 制作一个提交外部 URL( Outh/ OIDC) 的 HTML 格式
  • 播放认证更改到其他标签/窗口,并在更改到来时重新回复

账户菜单栏

页面上方的收缩栏 。 签名时显示"QQ用户名QQ签名出",或者签名出"签名出"按钮. 点击“ 签名” 打开 Authenticator 在一个模式上覆盖.

import { AccountMenuBar } from '@aws-blocks/auth-common/ui';
import { authApi } from 'aws-blocks';

document.body.prepend(AccountMenuBar(authApi));

使用 AccountMenuBar 用于页眉和 Authenticator 当您想要一个独立的登录形式(如专用登录页)时.

已认证

只有在用户签名时才会渲染内容. 当认证状态改变时自动更新( 相同的窗口和交叉 Tab) .

import { AuthenticatedContent } from '@aws-blocks/auth-common/ui';
import { authApi } from 'aws-blocks';

document.body.appendChild(
  AuthenticatedContent(authApi, (user) => {
    const el = document.createElement('div');
    el.textContent = `Welcome, ${user.username}`;
    return el;
  })
);

未认证用户的退后

在用户未签名时, 通过一个可选的第三个参数来显示替代内容 :

const loginPrompt = document.createElement('p');
loginPrompt.textContent = 'Please sign in to continue.';

document.body.appendChild(
  AuthenticatedContent(authApi, (user) => {
    const el = document.createElement('div');
    el.textContent = `Welcome, ${user.username}`;
    return el;
  }, loginPrompt)
);

在不提供倒置时,容器在签出(背向相容)时不产生任何结果.

状态

用于"加载/成功/出错"的有主题,可访问状态行 offernance appers 否则会带有内线样式的手卷. 它返回一个手柄:挂载 handle.element,然后用 handle.set(kind, text) 作为同步操作的进展.

import { StatusMessage } from '@aws-blocks/auth-common/ui';

const status = StatusMessage({ kind: 'loading', text: 'Loading…' });
document.querySelector('#app-status')!.replaceWith(status.element);

try {
  await saveSettings(); // your own async work
  status.set('success', 'Done.');
} catch (e) {
  status.set('error', `Failed: ${(e as Error).message}`);
}

该元素是一个礼貌的ARIA活区(ARIA活区)role="status", (中文(简体) ), aria-live="polite")),因此屏幕阅读器会在不偷取焦点的情况下宣布每次过渡. 这个 loading 状态让旋转者荣耀 prefers-reduced-motion。所有颜色来自共享 --bb-* 符号,所以它自动匹配活动光/暗主题.

kind外观
idle变音文本( e)--bb-color-text-muted(中文(简体) )
loading变音文本 + 动画自旋器
success绿色( e)--bb-color-success(中文(简体) )
error红色( r)--bb-color-danger(中文(简体) )

过 testId 范围 -text ),当一个页面使多个状态区域.

Auth 状态更改订阅

订阅任何来源的认证状态变化( 相同的窗口 + 其他标签) :

import { onAuthChange } from '@aws-blocks/auth-common/ui';
import { authApi } from 'aws-blocks';

const unsubscribe = onAuthChange(authApi, (user) => {
  if (user) {
    console.log('Signed in:', user.username);
  } else {
    console.log('Signed out');
  }
});

// Later: unsubscribe();

onAuthChange 立即与当前用户调用回调,然后再次调用每个更改.

广播认证更改

如果您构建自定义认证 UI 而不是使用 Authenticator,该应用程序仍需要知道 Auth 何时改变,所以其他组件和标签的反应。 使用 submitAuthAction 作为单一通知符:它提交动作,推进缓存状态,并在任何已签入/已签出过渡中广播,所以两个已签入 财务报告和审定财务报表 保持UI的反应.

import { submitAuthAction } from '@aws-blocks/auth-common/ui';
import { authApi } from 'aws-blocks';

// Sign-in: submits, updates the cache, and broadcasts the transition.
const next = await submitAuthAction(authApi, { action: 'signIn', username: 'alice', password: 'secret' });
if (next.retriable) showError(next.error); // wrong password / MFA code: re-prompt, nothing broadcast

// Sign-out is the SAME call. The broadcast fires on the transition, so
// AccountMenuBar, AuthenticatedContent, and other tabs update immediately.
await submitAuthAction(authApi, { action: 'signOut' });

submitAuthAction(api, input) 返回结果 AuthState。一个赤裸的 setAuthState 调用翻转服务器会话但通知 无 在客户端上,这就是为什么直接调用它的习惯UI会变得僵化(特别是在签出; 第185期). 这个 Authenticator 用途 submitAuthAction 内部,所以你得到这个免费 当你使用它.

broadcastAuthChange (低级原始)

broadcastAuthChange 是基础 广播原始 submitAuthAction 打电话 只在认证状态通过路径改变时直接联系它 submitAuthAction 不遮盖,你需要 推动变化自己:

import { broadcastAuthChange } from '@aws-blocks/auth-common/ui';

// After a successful sign-in
broadcastAuthChange({ userId: 'alice', username: 'alice' });

// After sign-out
broadcastAuthChange(null);
function broadcastAuthChange(user: AuthUser | null): void

通过报名 AuthUser,或 null 签了字 它发射一个 BroadcastChannel 其它标签的信息加当前标签的窗口事件,这是每个 onAuthChange 订户听取. 只有浏览器:它触摸 window所以在安保部门期间别叫它.

应用程序代码通常安装伞包而不是 auth-common,该导入是 @aws-blocks/blocks/ui数字 :

import { broadcastAuthChange, onAuthChange, Authenticator } from '@aws-blocks/blocks/ui';

词根 @aws-blocks/blocks 入境点不出口,因为UI出口在后面 /ui 子路径,所以后端捆绑 不拉在反应. @aws-blocks/auth-common/ui 财务报告和审定财务报表 @aws-blocks/blocks/ui 是同一函数; 使用伞形路径, 除非您依赖 auth-common 直接说.

这个 Authenticator 组件自动执行。 你们只需要 broadcastAuthChange 如果你正在建造定制的UI。 完全通过自定义UI,包括 setAuthState 循环和 AuthActionInput 合同,见 自定义 Auth 用户界面。 。 。 .

赛明会injectTheme + 键 --bb-* 符号)

UI组件将一个框架中性设计-托肯层船. 每个 构成部分Authenticator, (中文(简体) ), AccountMenuBar, (中文(简体) ), AuthenticatedContent(中文(简体) ) 向小样式表注入 document.head 这是第一次 因此,主题的外观 与组件 旅行到任何宿主 - lt-html, 香草 DOM, React, Next.js — 没有样式表可以导入 .

样式表是 CSS 自定义属性 :root (单位:千美元)--bb-color-*, (中文(简体) ), --bb-space-*, (中文(简体) ), --bb-radius-*, (中文(简体) ), --bb-font-*, (中文(简体) ), --bb-shadow-*) 加上 基础 .bb-* 组件类 。 灯光和 提供暗色调色板; 暗色由自动选择 prefers-color-scheme。 。 。 .

因为信物已经打开了 :root,你自己的标记 可以消耗它们为 一致的外观, 不导入任何东西 :

.my-button {
  background: var(--bb-color-accent);
  color: var(--bb-color-accent-text);
  border-radius: var(--bb-radius-sm);
  padding: var(--bb-space-2) var(--bb-space-4);
}

通过设置强制一个特定的调色板 data-bb-theme 任何祖传 (它胜过媒体查询):

<body data-bb-theme="dark"> ... </body>

打电话 injectTheme() 在任何纪念品之前 组件挂载(例如,在启动时以页面染色体为主题)。 这个 是天能地能的,是安全无虞的——第二次呼叫是无,它返回 无声无息 document数字 :

import { injectTheme } from '@aws-blocks/blocks/ui';

injectTheme();

THEME_CSS (样式表作为字符串)和 THEME_STYLE_ID (单位:千美元) <style> 元素的 id) 也被导出给捆绑 CSS 的主机 通过一个积分步骤或在测试中断言反对它.

类型

AuthState

归来 getAuthState() 财务报告和审定财务报表 setAuthState()。 。 。 .

外地类型说明
state'signedOut' | 'signedIn' | 'confirmingSignUp' | 'confirmingSignIn' | 'confirmingMfa' | 'confirmingPasswordReset'当前状态名称
userAuthUser?现时 state === 'signedIn'
actionsAuthAction[]此状态的现有动作
errorstring?上次动作出错
errorNamestring?最后动作出错的机器可读取名称, 镜像所抛出的 ApiError是因为 name (例如:. 'InvalidCredentialsException') (中文(简体) ). 有关它的分支 hasAuthError(state, name) 而不是与人类相配 error成功与否或通用 ApiError。 。 。 .
retriableboolean?上次行动恢复失败: 不变 状态( 保留隐藏字段, 如 session显示 error ,而不是重新启动流量.

AuthAction

所有的行动都是形式。 它们在提交文件方面有所不同.

外地类型说明
namestring动作名. 用作 action 歧视 setAuthState({ action, ...fields })。 。 。 .
labelstring按钮标签(如"Sign In","Sign in with Google"等)
fieldsAuthField[]窗体字段
urlstring?外部形式目标。 当存在时, 在此提交 HTML 表格而不是调用 setAuthState()。 。 。 .
method'GET' | 'POST'?外表的HTTP方法. 默认 : 'GET'。 。 。 .

AuthField

外地类型说明
namestring字段名称( 字段记录中的密钥)
labelstring可读标签
typestring'text', (中文(简体) ), 'password', (中文(简体) ), 'email', (中文(简体) ), 'tel', (中文(简体) ), 'number', (中文(简体) ), 'hidden'
requiredboolean是否需要字段
defaultValuestring?如果客户端不提供默认值

AuthUser

外地类型说明
userIdstring唯一标识符
usernamestring显示名称或用户名

提供商特有的BB扩展此段(例如:, AuthBasicUser 添加 createdAt) (中文(简体) ).

版本与发布记录

@aws-blocks/auth-common 共发布 15 个版本,首次发布于 2026/06/16;过去 12 个月发布了 15 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.3.0latest2026/11/025 天前
0.2.02026/10/1622 天前
0.0.0-canary.esql-canary.c93c81b.1791235863canary-esql-canary2026/10/061 个月前
0.1.92026/10/051 个月前
0.0.0-canary.esql-canary.f7f39ac.17909891272026/10/031 个月前
0.0.0-canary.ci-publish-canary-npm.f53dfdc.1790988617canary-ci-publish-canary-npm2026/10/031 个月前

关于 @aws-blocks/auth-common 的常见问题

@aws-blocks/auth-common 是什么?

AWS Blocks Auth Building Blocks的所有共享接口和UI组件. 使用此软件包来构建提供者- 不可知的 Author UI, 或者在创建自定义 Author Building Block 时导入类型 .

如何安装 @aws-blocks/auth-common?

在项目目录运行 npm install @aws-blocks/auth-common,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:constructs(^10.6.0)、aws-cdk-lib(^2.257.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-blocks/auth-common 支持 TypeScript 吗?

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

@aws-blocks/auth-common 支持 ESM 还是 CommonJS?

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

@aws-blocks/auth-common 可以商用吗?

@aws-blocks/auth-common 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws-blocks/auth-common 的下载量有多少?

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

@aws-blocks/auth-common 还在维护吗?

最新版本 0.3.0 发布于 2026/11/02(5 天前);至今共发布 15 个版本,其中过去 12 个月发布了 15 个;首次发布于 2026/06/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。