@aws-blocks/auth-common

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

Shared interfaces and UI components for all AWS Blocks auth Building Blocks. Use this package to build provider-agnostic auth UI, or import the types when authoring a custom auth Building Block.

原始使用文档
文档目录17 节
  1. Exports
  2. Session-cookie security policy ( /cookies )
  3. Server-Side Interface ( BlocksAuth )
  4. Authenticator Component
  5. AccountMenuBar
  6. AuthenticatedContent
  7. Fallback for unauthenticated users
  8. StatusMessage
  9. Auth State Change Subscription
  10. Broadcasting Auth Changes
  11. broadcastAuthChange (lower-level primitive)
  12. Theming ( injectTheme + --bb-* tokens)
  13. Types Reference
  14. AuthState
  15. AuthAction
  16. AuthField
  17. AuthUser

@aws-blocks/auth-common

Shared interfaces and UI components for all AWS Blocks auth Building Blocks. Use this package to build provider-agnostic auth UI, or import the types when authoring a custom auth Building Block.

Design & mock parity details: DESIGN.md

Exports

Export PathWhat it provides
@aws-blocks/auth-commonTypes: BlocksAuth, AuthUser, AuthState, AuthAction, AuthField
@aws-blocks/auth-common/uiComponents: AccountMenuBar, Authenticator, AuthenticatedContent, StatusMessage, onAuthChange, broadcastAuthChange, submitAuthAction; theme: injectTheme, THEME_CSS, THEME_STYLE_ID
@aws-blocks/auth-common/themeDesign-token layer: injectTheme, THEME_CSS, THEME_STYLE_ID
@aws-blocks/auth-common/cookiesShared session-cookie security policy: resolveCookieSecurity, buildCookieSecurityAttrs, isLoopbackRequest, isInsecurePublicOrigin

All AWS Blocks auth BBs route their session-cookie SameSite / Secure / Partitioned selection through this one helper, so they converge structurally instead of drifting. Given { crossDomain, isLocalhost } it returns the canonical attributes:

crossDomainisLocalhostattributes
false (default)falseSameSite=Lax; Secure
falsetrueSameSite=Lax
truefalseSameSite=None; Secure; Partitioned
truetrueSameSite=None; Secure

buildCookieSecurityAttrs(input) returns the string form for BBs that assemble Set-Cookie by hand; resolveCookieSecurity(input) returns the attribute object for BBs that pass a structured cookie config. isLoopbackRequest(ctx) detects loopback origins (localhost, 127.0.0.1, [::1]) for per-request isLocalhost decisions.

The optional plainHttpOrigin input marks a deployed front door served over plain HTTP (an ALB with no certificate): it drops Secure from the same-origin Lax cookie, which a browser would otherwise discard over HTTP. It doesn't change the cross-domain cookie, which the API's own HTTPS response sets. isInsecurePublicOrigin() derives it from the door's own scheme (BLOCKS_PUBLIC_ORIGIN starting with http://), never from a request header. Today bb-auth-basic passes it; the other auth BBs keep Secure, so behind a plain-HTTP door their sessions don't persist.

Server-Side Interface (BlocksAuth)

All auth BBs implement BlocksAuth. Server-side code is identical regardless of provider:

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();
MethodReturnsWhen to use
requireAuth(context)Promise<AuthUser>Protected endpoints. Throws 401 if not signed in.
checkAuth(context)Promise<boolean>Branching logic.
getCurrentUser(context)Promise<AuthUser | null>Optional personalization.

Authenticator Component

The Authenticator renders auth UI driven by the state machine. It works with any auth provider — AuthBasic, AuthOIDC, AuthCognito — because it renders based on AuthState, not provider-specific logic.

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

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

To restyle, relabel, hide, or fully replace the rendered forms, see Customizing Auth UI.

The component:

  • Calls getAuthState() on mount to determine what to render
  • Renders form fields and submit buttons for each available action
  • For internal actions (no url): collects input and calls setAuthState({ action, ...fields })
  • For external actions (with url): renders an HTML form that submits to the external URL (OAuth/OIDC)
  • Broadcasts auth changes to other tabs/windows and re-renders when changes arrive

AccountMenuBar

Compact bar for the top of the page. Shows "👤 username | Sign Out" when signed in, or a "Sign In" button when signed out. Clicking "Sign In" opens the Authenticator in a modal overlay.

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

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

Use AccountMenuBar for the page header and Authenticator when you want a standalone sign-in form (e.g., a dedicated login page).

AuthenticatedContent

Renders content only when the user is signed in. Automatically updates when auth state changes (same window and cross-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;
  })
);

Fallback for unauthenticated users

Pass an optional third argument to display alternative content when the user is NOT signed in:

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)
);

When no fallback is provided the container renders nothing while signed out (backward-compatible).

StatusMessage

A themed, accessible status line for the "loading / success / error" affordance apps otherwise hand-roll with inline styles. It returns a handle: mount handle.element, then drive it with handle.set(kind, text) as an async operation progresses.

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}`);
}

The element is a polite ARIA live region (role="status", aria-live="polite"), so a screen reader announces each transition without stealing focus. The loading state renders a spinner that honors prefers-reduced-motion. All colors come from the shared --bb-* tokens, so it matches the active light/dark theme automatically.

kindAppearance
idlemuted text (--bb-color-text-muted)
loadingmuted text + animated spinner
successgreen (--bb-color-success)
errorred (--bb-color-danger)

Pass testId to scope the root (and its -text child) when a page renders more than one status region.

Auth State Change Subscription

Subscribe to auth state changes from any source (same window + other tabs):

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 calls the callback immediately with the current user, then again on every change.

Broadcasting Auth Changes

If you build custom auth UI instead of using the Authenticator, the app still needs to know when auth changed so other components and tabs react. Use submitAuthAction as the single notifier: it submits the action, advances the cached state, and broadcasts on any signed-in / signed-out transition, so both sign-in and sign-out keep the UI reactive.

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) returns the resulting AuthState. A bare setAuthState call flips the server session but notifies nothing on the client, which is why custom UI that calls it directly goes stale (notably on sign-out; issue #185). The Authenticator uses submitAuthAction internally, so you get this for free when you use it.

broadcastAuthChange (lower-level primitive)

broadcastAuthChange is the underlying broadcast primitive that submitAuthAction calls. Reach for it directly only when auth state changed through a path submitAuthAction doesn't cover and you need to fan the change out yourself:

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

Pass the signed-in AuthUser, or null for a sign-out. It fires a BroadcastChannel message for other tabs plus a window event for the current tab, which is what every onAuthChange subscriber listens to. It is browser-only: it touches window, so don't call it during SSR.

Application code normally installs the umbrella package rather than auth-common, and there the import is @aws-blocks/blocks/ui:

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

The root @aws-blocks/blocks entry point does not export it, because the UI exports live behind the /ui subpath so backend bundles don't pull in React. @aws-blocks/auth-common/ui and @aws-blocks/blocks/ui are the same function; use the umbrella path unless you depend on auth-common directly.

The Authenticator component does this automatically. You only need broadcastAuthChange if you're building custom UI. For a full walkthrough of custom UI, including the setAuthState loop and the AuthActionInput contract, see Customizing Auth UI.

Theming (injectTheme + --bb-* tokens)

The UI components ship a framework-neutral design-token layer. Each component (Authenticator, AccountMenuBar, AuthenticatedContent) injects a small stylesheet into document.head the first time it renders, so the themed look travels with the component into any host — lit-html, vanilla DOM, React, Next.js — with no stylesheet to import.

The stylesheet is CSS custom properties on :root (--bb-color-*, --bb-space-*, --bb-radius-*, --bb-font-*, --bb-shadow-*) plus the base .bb-* component classes the components render against. A light and a dark palette are provided; dark is selected automatically by prefers-color-scheme.

Because the tokens are on :root, your own markup can consume them for a consistent look without importing anything:

.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);
}

Force a specific palette by setting data-bb-theme on any ancestor (it wins over the media query):

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

Call injectTheme() yourself to make the tokens available before any component mounts (for example, to theme your page chrome at startup). It is idempotent and SSR-safe — a second call is a no-op, and it returns silently when there is no document:

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

injectTheme();

THEME_CSS (the stylesheet as a string) and THEME_STYLE_ID (the <style> element's id) are also exported for hosts that bundle the CSS through a build step or assert against it in tests.

Types Reference

AuthState

Returned by getAuthState() and setAuthState().

FieldTypeDescription
state'signedOut' | 'signedIn' | 'confirmingSignUp' | 'confirmingSignIn' | 'confirmingMfa' | 'confirmingPasswordReset'Current state name
userAuthUser?Present when state === 'signedIn'
actionsAuthAction[]Available actions from this state
errorstring?Error from the last action
errorNamestring?Machine-readable name of the last action's error, mirroring the thrown ApiError's name (e.g. 'InvalidCredentialsException'). Branch on it with hasAuthError(state, name) instead of matching the human-facing error. Absent on success or a generic ApiError.
retriableboolean?The last action failed recoverably: resubmit on the same state (preserving hidden fields such as session) and show error inline, instead of restarting the flow.

AuthAction

All actions are forms. They differ in where they submit.

FieldTypeDescription
namestringAction name. Used as the action discriminant in setAuthState({ action, ...fields }).
labelstringButton label (e.g., "Sign In", "Sign in with Google")
fieldsAuthField[]Form fields
urlstring?External form target. When present, submit an HTML form here instead of calling setAuthState().
method'GET' | 'POST'?HTTP method for external forms. Default: 'GET'.

AuthField

FieldTypeDescription
namestringField name (key in the fields record)
labelstringHuman-readable label
typestring'text', 'password', 'email', 'tel', 'number', 'hidden'
requiredbooleanWhether the field is required
defaultValuestring?Default value if the client doesn't provide one

AuthUser

FieldTypeDescription
userIdstringUnique identifier
usernamestringDisplay name or username

Provider-specific BBs extend this (e.g., AuthBasicUser adds 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 是什么?

Shared interfaces and UI components for all AWS Blocks auth Building Blocks. Use this package to build provider-agnostic auth UI, or import the types when authoring a custom auth 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 和提交记录判断。