aws-auth

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS Auth (Amazon Cognito)

AWS认证(Amazon Cognito)

Application-level user authentication and authorization with Amazon Cognito and the Amplify client auth libraries. Verify specific limits, quotas, and exact API shapes against official AWS documentation when precision matters; trust the docs over memory when they conflict.
Recommended: The AWS MCP server provides streamlined access to the AWS APIs used in this skill (Cognito user pool/app client/identity pool setup, API Gateway authorizers). If it is unavailable, the AWS CLI commands shown throughout work directly — the skill has no hard dependency on MCP.
When NOT to use: Amplify Gen2 backend code (
defineAuth
,
amplify/auth.ts
,
npx ampx
); IAM policy/role/trust-policy authoring, STS, or IAM Identity Center console SSO; API Gateway route/integration setup or Lambda function implementation (this skill covers only the Cognito/JWT authorizer configuration and the purpose of Cognito Lambda triggers).
基于Amazon Cognito和Amplify客户端认证库的应用级用户认证与授权。当需要精确信息时,请参考AWS官方文档验证具体的限制、配额和API结构;若文档与记忆内容冲突,以文档为准。
推荐方案: AWS MCP服务器可简化对本技能中用到的AWS API的访问(Cognito用户池/应用客户端/身份池设置、API Gateway授权方)。若MCP不可用,本文中展示的AWS CLI命令可直接使用——本技能不依赖MCP。
不适用于: Amplify Gen2后端代码(
defineAuth
amplify/auth.ts
npx ampx
);IAM策略/角色/信任策略编写、STS或IAM Identity Center控制台单点登录;API Gateway路由/集成设置或Lambda函数实现(本技能仅涵盖Cognito/JWT授权方配置以及Cognito Lambda触发器的用途)。

User Pool vs Identity Pool — pick first

用户池 vs 身份池 — 先做选择

These are different services that are frequently confused. Most apps need a user pool; add an identity pool only if the client must call AWS services directly.
You need...UseWhy
Sign-up / sign-in, user directory, issue JWTsUser poolIt authenticates users and is an OIDC IdP
The signed-in client to call S3/DynamoDB/etc. directly with AWS credentialsIdentity poolIt exchanges a token for temporary AWS credentials via STS
Both (sign in, then hit AWS resources from the browser/app)User pool → identity poolIdentity pool trusts the user pool as its IdP
If your app only calls your own backend/API, you do not need an identity pool — send the user pool token to your API. See identity-pools.md.
这是两种常被混淆的不同服务。大多数应用需要用户池;仅当客户端需要直接调用AWS服务时,才添加身份池
你需要...使用原因
注册/登录、用户目录、签发JWT用户池它负责认证用户,是OIDC身份提供商(IdP)
已登录客户端使用AWS凭证直接调用S3/DynamoDB等服务身份池它通过STS将令牌兑换为临时AWS凭证
两者兼具(登录后从浏览器/应用访问AWS资源)用户池 → 身份池身份池信任用户池作为其身份提供商
如果你的应用仅调用自有后端/API,则不需要身份池——将用户池令牌发送至API即可。详见identity-pools.md

Critical Warnings

重要警告

update-user-pool-client
and
set-identity-pool-roles
are FULL REPLACE, not partial updates
: Any field you omit is reset to its default — calling
update-user-pool-client
with only the fields you want to change silently wipes
ExplicitAuthFlows
, token validity,
EnableTokenRevocation
, refresh-token rotation, and read/write attributes;
set-identity-pool-roles
likewise replaces the whole roles +
RoleMappings
structure. Always read-modify-write:
describe-user-pool-client
(or
get-identity-pool-roles
) first, then re-send every existing field plus your change. In an agent context the wipe is invisible — the call succeeds and only breaks later when a user hits the missing flow. See managed-login-oauth.md and identity-pools.md.
Don't use the implicit grant for new apps: The implicit grant (
response_type=token
) is legacy and returns tokens in the URL fragment. Use the authorization code grant with PKCE (
response_type=code
+
code_challenge
) for SPAs and mobile — public clients, no client secret. See managed-login-oauth.md.
Don't store refresh tokens in localStorage for high-value apps:
localStorage
is readable by any injected script (XSS). The Amplify client library defaults to
localStorage
; switch to
cookieStorage
, keep refresh-token lifetime short, and enable refresh token rotation + token revocation on the app client. See tokens-and-sessions.md.
Access-token claim customization needs a paid feature plan: The pre token generation trigger customizes the ID token on the entry-level plan (V1), but customizing the access token (V2/V3) requires a paid feature plan — check the Cognito feature plans documentation for which plan currently includes this, as plan names and inclusions can change. Don't assume access-token claims work on the entry-level plan. See lambda-triggers.md.
App client secret + SPA = broken auth: A public client (browser/mobile) must have no client secret. If a secret is set, token calls fail unless a
SECRET_HASH
is sent, which a browser cannot protect. Generate a secret only for confidential (server-side) clients.
Don't bulk
admin-confirm-sign-up
UNCONFIRMED users
: When users are stuck
UNCONFIRMED
, prefer
resend-confirmation-code
so each user re-verifies via
confirm-sign-up
and proves email ownership (the code likely expired or went to spam).
admin-confirm-sign-up
flips the status instantly but confirms the account without verifying the email — the attribute stays unverified, which is dangerous when email drives password reset or account linking. Reserve it for trusted/migrated accounts. See troubleshooting.md.
update-user-pool-client
set-identity-pool-roles
是全量替换,而非部分更新
:任何你省略的字段都会被重置为默认值——调用
update-user-pool-client
时仅传入你想修改的字段,会静默清除
ExplicitAuthFlows
、令牌有效期、
EnableTokenRevocation
、刷新令牌轮换以及读写属性;
set-identity-pool-roles
同样会替换整个角色+
RoleMappings
结构。务必遵循读取-修改-写入流程:先调用
describe-user-pool-client
(或
get-identity-pool-roles
),然后重新发送所有现有字段加上你要修改的内容。在Agent场景下,这种清除操作是不可见的——调用会成功,但后续用户使用缺失的流程时会出现问题。详见managed-login-oauth.mdidentity-pools.md
新应用请勿使用隐式授权:隐式授权(
response_type=token
)是遗留方案,会在URL片段中返回令牌。对于SPA和移动应用(公共客户端,无客户端密钥),请使用带PKCE的授权码授权
response_type=code
+
code_challenge
)。详见managed-login-oauth.md
高价值应用请勿将刷新令牌存储在localStorage中
localStorage
可被任何注入脚本读取(XSS攻击)。Amplify客户端库默认使用
localStorage
;请切换为
cookieStorage
,缩短刷新令牌有效期,并在应用客户端上启用刷新令牌轮换令牌吊销功能。详见tokens-and-sessions.md
自定义访问令牌声明需要付费功能套餐:预令牌生成触发器在入门级套餐(V1)中可自定义ID令牌,但自定义访问令牌(V2/V3)需要付费功能套餐——请查看Cognito功能套餐文档了解当前包含该功能的套餐,因为套餐名称和包含内容可能会变化。不要默认认为入门级套餐支持访问令牌声明自定义。详见lambda-triggers.md
应用客户端密钥 + SPA = 认证失效:公共客户端(浏览器/移动应用)必须无客户端密钥。如果设置了密钥,除非发送
SECRET_HASH
,否则令牌调用会失败,而浏览器无法保护该哈希值。仅为机密(服务器端)客户端生成密钥。
请勿批量对UNCONFIRMED用户执行
admin-confirm-sign-up
:当用户处于
UNCONFIRMED
状态时,优先使用
resend-confirmation-code
,让用户通过
confirm-sign-up
重新验证并证明邮箱所有权(验证码可能已过期或进入垃圾邮件)。
admin-confirm-sign-up
会立即更改状态,但未验证邮箱就确认账户——该属性仍处于未验证状态,当邮箱用于重置密码或账户关联时会很危险。仅对可信/迁移账户使用此操作。详见troubleshooting.md

Quick Navigation

快速导航

You want to...Go to
Create a user pool, sign-up/sign-in, MFA, password policy, app clientsuser-pools.md
Add hosted UI / managed login, OAuth flows, social or SAML login, callback URLs, custom domain (ACM in us-east-1)managed-login-oauth.md
Handle ID/access/refresh tokens, rotation, revocation, session termination (global sign-out vs revoke vs disable)tokens-and-sessions.md
Give the client temporary AWS credentials, guest access, role mappingidentity-pools.md
Protect an API Gateway API with Cognito tokens (and enforce custom claims in the backend)api-authorization.md
Add Cognito login in front of an Application Load Balancer (ALB
authenticate-cognito
)
api-authorization.md
Machine-to-machine (client credentials) auth, resource servers, custom scopesmanaged-login-oauth.md
Create user pool groups and add users to them (
cognito:groups
,
Precedence
)
user-pools.md
Customize claims, custom auth challenge flows, migrate users, validate sign-uplambda-triggers.md
Add passkey / WebAuthn sign-in (
USER_AUTH
flow,
AllowedFirstAuthFactors
, WebAuthn enrollment)
passkeys.md
Configure threat protection — compromised-credentials block, adaptive auth (risk-based MFA), log delivery to CloudWatchthreat-protection.md
Something is broken (redirect, token, MFA, CORS, social login)troubleshooting.md
你想...前往
创建用户池、注册/登录、MFA、密码策略、应用客户端user-pools.md
添加托管UI/托管登录、OAuth流程、社交或SAML登录、回调URL、自定义域名(us-east-1区域的ACM)managed-login-oauth.md
处理ID/访问/刷新令牌、轮换、吊销、会话终止(全局登出vs吊销vs禁用)tokens-and-sessions.md
为客户端提供临时AWS凭证、访客访问、角色映射identity-pools.md
用Cognito令牌保护API Gateway API(并在后端强制执行自定义声明api-authorization.md
在应用负载均衡器(ALB
authenticate-cognito
)前添加Cognito登录
api-authorization.md
机器对机器(客户端凭证)认证、资源服务器、自定义范围managed-login-oauth.md
创建用户池组并添加用户(
cognito:groups
Precedence
user-pools.md
自定义声明、自定义认证挑战流程、迁移用户、验证注册lambda-triggers.md
添加密钥/WebAuthn登录(
USER_AUTH
流程、
AllowedFirstAuthFactors
、WebAuthn注册)
passkeys.md
配置威胁防护——泄露凭证拦截、自适应认证(基于风险的MFA)、日志投递到CloudWatchthreat-protection.md
出现故障(重定向、令牌、MFA、CORS、社交登录)troubleshooting.md

Common Workflows

常见工作流

"Add sign-up and login to my React app" → Create a user pool + a public app client (no secret), enable the hosted UI / managed login with the authorization code grant with PKCE, wire the Amplify client library. See user-pools.md and managed-login-oauth.md.
"Add Google / social login" → Register the social IdP on the user pool, map attributes, add the provider to the app client and hosted UI. See managed-login-oauth.md.
"Only authenticated users should call my API" → HTTP API → JWT authorizer; REST API → Cognito user pools authorizer. See api-authorization.md.
"Let the browser upload to S3 after login" → User pool for sign-in, then an identity pool to vend scoped temporary credentials. See identity-pools.md.
“为我的React应用添加注册和登录功能” → 创建用户池+公共应用客户端(无密钥),启用带PKCE的授权码授权的托管UI/托管登录,集成Amplify客户端库。详见user-pools.mdmanaged-login-oauth.md
“添加谷歌/社交登录” → 在用户池上注册社交身份提供商,映射属性,将提供商添加到应用客户端和托管UI。详见managed-login-oauth.md
“仅允许已认证用户调用我的API” → HTTP API → JWT授权方;REST API → Cognito用户池授权方。详见api-authorization.md
“允许浏览器登录后上传到S3” → 用户池用于登录,然后通过身份池提供限定范围的临时凭证。详见identity-pools.md

Troubleshooting

故障排查

Error/SymptomLikely CauseQuick Fix
redirect_mismatch
/ redirect to wrong URL after login
Callback URL not registered, or scheme/trailing-slash/case differsAdd the exact callback URL (incl. scheme and path) to the app client's Allowed callback URLs
Token calls fail with "unable to verify secret hash"Client secret set on a public (SPA/mobile) clientRecreate the app client with no secret, or send
SECRET_HASH
from a confidential client
Users get 401 from API Gateway with a valid tokenWrong token type or audience/issuer mismatchHTTP JWT authorizer: issuer
https://cognito-idp.{region}.amazonaws.com/{userPoolId}
, audience = app client id; send the token the authorizer expects
CORS errors calling the hosted UI / token endpointBrowser calling
/oauth2/token
cross-origin, or missing CORS on your API
Do the code exchange with PKCE; don't proxy the token endpoint from the browser
Social login user "already exists" / attribute conflictSame email across providers creates separate usersEnable attribute mapping + account linking; treat email as non-unique across IdPs
Full tables in troubleshooting.md.
错误/症状可能原因快速修复
redirect_mismatch
/ 登录后重定向到错误URL
回调URL未注册,或协议/尾斜杠/大小写不一致将精确的回调URL(包含协议和路径)添加到应用客户端的允许回调URL列表中
令牌调用失败,提示“无法验证秘密哈希”公共(SPA/移动)客户端设置了客户端密钥重新创建无密钥的应用客户端,或从机密客户端发送
SECRET_HASH
用户使用有效令牌访问API Gateway时收到401错误令牌类型错误或受众/颁发者不匹配HTTP JWT授权方:颁发者为
https://cognito-idp.{region}.amazonaws.com/{userPoolId}
,受众=应用客户端ID;发送授权方所需的令牌
调用托管UI/令牌端点时出现CORS错误浏览器跨域调用
/oauth2/token
,或API缺少CORS配置
使用PKCE完成代码交换;不要从浏览器代理令牌端点
社交登录用户提示“已存在”/属性冲突不同提供商的同一邮箱创建了不同用户启用属性映射+账户关联;将邮箱视为跨身份提供商非唯一属性
完整表格详见troubleshooting.md

Security Considerations

安全注意事项

  • Public clients (SPA/mobile): no client secret, authorization code grant with PKCE, request least-privilege scopes.
  • Enable MFA (TOTP or SMS), a strong password policy, and advanced security / threat protection where available.
  • Short access-token lifetime; enable refresh token rotation and token revocation; prefer
    cookieStorage
    over
    localStorage
    .
  • Identity pools: scope the authenticated IAM role tightly; disable unauthenticated (guest) access unless required.
  • Validate JWTs against the user pool JWKS (
    iss
    ,
    aud
    /
    client_id
    ,
    token_use
    ,
    exp
    ) on every protected request. Use a maintained library such as
    aws-jwt-verify
    rather than hand-rolling verification.
  • Set security headers on the app's web pages:
    Content-Security-Policy
    (restrict script sources to mitigate token-stealing XSS),
    Strict-Transport-Security
    (HSTS),
    X-Frame-Options
    /
    frame-ancestors
    (clickjacking on login pages), and
    X-Content-Type-Options: nosniff
    .
  • Enable logging and monitoring: CloudTrail for Cognito API events (sign-up/sign-in/admin), user pool threat protection (adaptive auth + event logging), CloudWatch alarms on failed/throttled auth, and API Gateway access logging for authorizer decisions.
  • All Cognito and API endpoints are HTTPS/TLS only; enable encryption at rest with a customer-managed KMS key (and restricted key access) on CloudWatch Log groups, SNS topics used for MFA/notifications, and any identity-pool-fronted upload buckets.
  • If using SNS for MFA/notification delivery, enable server-side encryption (KMS) on the topic, and keep SMS/email message content limited to what the recipient needs — don't include more PII than the message requires.
  • References: Amazon Cognito security features (user pools), Amazon Cognito security (top-level, incl. identity pools), and IAM/STS best practices.
  • 公共客户端(SPA/移动):无客户端密钥,使用带PKCE的授权码授权,请求最小权限范围。
  • 启用MFA(TOTP或SMS)、强密码策略,以及可用的高级安全/威胁防护功能。
  • 缩短访问令牌有效期;启用刷新令牌轮换令牌吊销;优先使用
    cookieStorage
    而非
    localStorage
  • 身份池:严格限定已认证IAM角色的权限;除非必要,否则禁用未认证(访客)访问。
  • 在每个受保护请求中,根据用户池JWKS验证JWT(
    iss
    aud
    /
    client_id
    token_use
    exp
    )。使用维护良好的库(如
    aws-jwt-verify
    )而非手动编写验证逻辑。
  • 在应用网页上设置安全头:
    Content-Security-Policy
    (限制脚本源以缓解令牌窃取型XSS攻击)、
    Strict-Transport-Security
    (HSTS)、
    X-Frame-Options
    /
    frame-ancestors
    (防止登录页面点击劫持),以及
    X-Content-Type-Options: nosniff
  • 启用日志和监控:CloudTrail用于Cognito API事件(注册/登录/管理员操作)、用户池威胁防护(自适应认证+事件日志)、CloudWatch告警用于失败/限流的认证请求,以及API Gateway访问日志用于授权方决策。
  • 所有Cognito和API端点仅支持HTTPS/TLS;对CloudWatch日志组、用于MFA/通知的SNS主题,以及任何由身份池提供支持的存储桶,使用客户管理的KMS密钥启用静态加密(并限制密钥访问)。
  • 如果使用SNS进行MFA/通知发送,在主题上启用服务器端加密(KMS),并将SMS/邮件内容限制为收件人所需的信息——不要包含超出消息需要的个人身份信息(PII)。
  • 参考文档:Amazon Cognito安全功能(用户池)Amazon Cognito安全(顶层,含身份池),以及IAM/STS最佳实践

Where to Look When This Skill Is Silent

本技能未覆盖的内容查询途径

When you need depth beyond this skill — exact parameter shapes, current limits, edge behaviors — fall back to the authoritative AWS sources rather than guessing. Pointers age much slower than content, so this map stays useful without the skill having to grow.
当你需要超出本技能的深度信息——精确的参数结构、当前限制、边缘行为时,请参考权威的AWS资源而非猜测。这些链接的时效性远高于内容,因此即使技能内容未更新,该指引仍保持有用。

Not Covered By This Skill

本技能未覆盖的内容

  • Amplify Gen2 backend (
    defineAuth
    ,
    amplify/auth.ts
    ,
    npx ampx sandbox
    ).
  • IAM policy/role/trust-policy authoring, STS, IAM Identity Center console SSO.
  • API Gateway route/integration setup and Lambda function implementation (this skill covers only the Cognito/JWT authorizer configuration and the purpose of Cognito Lambda triggers).
  • Amplify Gen2后端
    defineAuth
    amplify/auth.ts
    npx ampx sandbox
    )。
  • IAM策略/角色/信任策略编写、STS、IAM Identity Center控制台单点登录
  • API Gateway路由/集成设置和Lambda函数实现(本技能仅涵盖Cognito/JWT授权方配置以及Cognito Lambda触发器的用途)。