Implement Authentication And/Or Authorization For Applications And AWS Services | 🏗️ Build A Secure Notes API

Implement Authentication And/Or Authorization For Applications And AWS Services | 🏗️ Build A Secure Notes API

实现应用程序和 AWS 服务的身份验证和/或授权 | 🏗️ 构建安全的笔记 API

Exam Guide: Developer - Associate 🏗️ Domain 2: Security 📘 Task 1: Implement Authentication And/Or Authorisation For Applications And AWS Services 考试指南:开发人员 - 助理级 🏗️ 领域 2:安全性 📘 任务 1:为应用程序和 AWS 服务实现身份验证和/或授权

Authentication (who are you?) and Authorisation (what can you do?) are central to the DVA-C02, and just Cloud Development in general. You need to know Cognito, IAM Roles and Policies, STS, Lambda Authorizers, and how to secure microservice-to-microservice communication or communication within a Microservices Architectural Environment. 身份验证(你是谁?)和授权(你能做什么?)是 DVA-C02 考试以及整个云开发的核心。你需要掌握 Cognito、IAM 角色与策略、STS、Lambda 授权器,以及如何保护微服务之间的通信或微服务架构环境内的通信。

📘 Concepts

📘 概念

TermWhat It AnswersAWS Services
AuthenticationWho are you?Cognito User Pools, IAM
AuthorisationWhat can you do?IAM Policies, Cognito Identity Pools, Lambda Authorizers
术语回答的问题AWS 服务
身份验证 (Authentication)你是谁?Cognito 用户池 (User Pools), IAM
授权 (Authorisation)你能做什么?IAM 策略, Cognito 身份池 (Identity Pools), Lambda 授权器

Amazon Cognito User Pools vs Identity Pools

Amazon Cognito 用户池与身份池对比

FeatureUser PoolIdentity Pool
PurposeAuthentication (sign up, sign in)Authorisation (temporary AWS credentials)
ReturnsJWT tokens (ID, access, refresh)AWS credentials (access key, secret, session token)
Use WhenYou need a user directoryUsers need to call AWS services directly
FederationGoogle, Facebook, SAML, OIDCGoogle, Facebook, SAML, User Pools
特性用户池 (User Pool)身份池 (Identity Pool)
目的身份验证(注册、登录)授权(临时 AWS 凭证)
返回内容JWT 令牌 (ID, access, refresh)AWS 凭证 (access key, secret, session token)
使用场景需要用户目录时用户需要直接调用 AWS 服务时
联合身份Google, Facebook, SAML, OIDCGoogle, Facebook, SAML, 用户池

User Pools = authentication (get tokens). Identity Pools = authorisation (get AWS credentials). They’re often used together but serve different purposes. 用户池 = 身份验证(获取令牌)。身份池 = 授权(获取 AWS 凭证)。它们通常一起使用,但用途不同。

The Three Cognito Tokens

三种 Cognito 令牌

  • ID Token: User identity claims (name, email, groups) -> Your application to identify the user.

  • Access Token: Scopes and permissions -> API authorisation.

  • Refresh Token: Long-lived credential -> Getting new ID/access tokens without re-authentication.

  • ID 令牌:用户身份声明(姓名、电子邮件、组) -> 用于应用程序识别用户。

  • 访问令牌 (Access Token):范围和权限 -> 用于 API 授权。

  • 刷新令牌 (Refresh Token):长期凭证 -> 在无需重新身份验证的情况下获取新的 ID/访问令牌。

API Gateway Authorisation Options

API 网关授权选项

  • None: No auth -> Public APIs.

  • IAM: SigV4 signing -> Internal/service-to-service calls.

  • Cognito Authorizer: Validates JWTs from User Pool -> Simple JWT validation.

  • Lambda Authorizer (Token): Custom logic on the token -> Complex auth, external IDPs.

  • Lambda Authorizer (Request): Custom logic on full request -> Auth based on headers, query strings, source IP.

  • 无 (None):无需验证 -> 公共 API。

  • IAM:SigV4 签名 -> 内部/服务间调用。

  • Cognito 授权器:验证来自用户池的 JWT -> 简单的 JWT 验证。

  • Lambda 授权器 (Token):基于令牌的自定义逻辑 -> 复杂的身份验证、外部身份提供商 (IDP)。

  • Lambda 授权器 (Request):基于完整请求的自定义逻辑 -> 基于标头、查询字符串、源 IP 的身份验证。

IAM Roles vs Users

IAM 角色与用户对比

  • IAM User: Long-lived (access key + secret) -> Humans, legacy CLI access.

  • IAM Role: Temporary (via STS AssumeRole) -> Applications, EC2, Lambda, cross-account.

  • IAM 用户:长期有效(访问密钥 + 密钥) -> 人员、遗留的 CLI 访问。

  • IAM 角色:临时有效(通过 STS AssumeRole) -> 应用程序、EC2、Lambda、跨账户访问。

Roles are always preferred for applications. Never hardcode access keys. Lambda uses an execution role, EC2 uses an instance profile, ECS uses a task role. All of these give your code temporary credentials automatically. 对于应用程序,始终首选角色。切勿硬编码访问密钥。Lambda 使用执行角色,EC2 使用实例配置文件,ECS 使用任务角色。所有这些都会自动为你的代码提供临时凭证。

STS (Security Token Service) Operations

STS (安全令牌服务) 操作

  • AssumeRole: Same or cross-account role assumption.

  • AssumeRoleWithWebIdentity: Exchange OAuth/OIDC token for AWS credentials.

  • AssumeRoleWithSAML: Exchange SAML assertion for AWS credentials.

  • GetSessionToken: Temporary credentials (for MFA-protected API calls).

  • AssumeRole:相同或跨账户的角色承担。

  • AssumeRoleWithWebIdentity:将 OAuth/OIDC 令牌交换为 AWS 凭证。

  • AssumeRoleWithSAML:将 SAML 断言交换为 AWS 凭证。

  • GetSessionToken:临时凭证(用于受 MFA 保护的 API 调用)。

Credential Resolution Order (SDK Default Chain)

凭证解析顺序 (SDK 默认链)

The AWS SDK looks for credentials in this order: AWS SDK 按以下顺序查找凭证:

  1. Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) -> 环境变量
  2. Shared credentials file (~/.aws/credentials) -> 共享凭证文件
  3. AWS config file (~/.aws/config) -> AWS 配置文件
  4. Container credentials (ECS task role) -> 容器凭证 (ECS 任务角色)
  5. Instance profile (EC2 role) -> 实例配置文件 (EC2 角色)
  6. SSO credentials (IAM Identity Center) -> SSO 凭证 (IAM Identity Center)

🏗️ Build A Secure Notes API

🏗️ 构建安全的笔记 API

Now lets put these concepts into practice, by building a Secure Notes API with Cognito authentication: 现在,让我们通过构建一个带有 Cognito 身份验证的“安全笔记 API”来实践这些概念:

  • A Cognito User Pool with Managed Login for sign-up/sign-in.

  • An App Client configured with the authorization code grant flow.

  • A Lambda function that stores and retrieves notes.

  • An API Gateway REST API protected by a Cognito authorizer.

  • Test users signing in and calling the API with JWT tokens.

  • 一个带有托管登录 (Managed Login) 功能的 Cognito 用户池,用于注册/登录。

  • 一个配置了授权码授予流程 (Authorization Code Grant Flow) 的应用程序客户端。

  • 一个用于存储和检索笔记的 Lambda 函数。

  • 一个由 Cognito 授权器保护的 API 网关 REST API。

  • 测试用户登录并使用 JWT 令牌调用 API。

Prerequisites: An AWS account. 先决条件:一个 AWS 账户。

Part I: Create the Cognito User Pool

第一部分:创建 Cognito 用户池

The Cognito console now uses a streamlined, application-focused setup wizard with Managed Login (the successor to the classic Hosted UI). The wizard creates your user pool and app client in one flow. Cognito 控制台现在使用一种精简的、以应用程序为中心的设置向导,并配备了托管登录(经典托管 UI 的继任者)。该向导可以在一个流程中创建你的用户池和应用程序客户端。

  • Step 01: Open the Cognito console.

  • Step 02: Click Create user pool.

  • Step 03: Set up resources for your application:

    • Application type: Traditional web application.
    • Name your application: My Notes App.
    • Options for sign-in identifiers: Email.
    • Self-registration: ✔
    • Required attributes for sign-up: email, name.
  • Step 04: Click Create user directory.

  • 步骤 01:打开 Cognito 控制台。

  • 步骤 02:点击“创建用户池”。

  • 步骤 03:为你的应用程序设置资源:

    • 应用程序类型:传统 Web 应用程序。
    • 应用程序名称:My Notes App。
    • 登录标识符选项:电子邮件。
    • 自助注册:✔
    • 注册所需属性:电子邮件、姓名。
  • 步骤 04:点击“创建用户目录”。

✅ Green banner: Your application “My Notes App” and user pool “User pool - gcvhqy” have been created successfully! ✅ 绿色横幅:你的应用程序“My Notes App”和用户池“User pool - gcvhqy”已成功创建!

💡 The new console creates the user pool, app client, and managed login domain all in one step. “Traditional web application” configures the authorization code grant flow with a client secret by default. This is the recommended pattern for server-side apps. 💡 新控制台一步即可创建用户池、应用程序客户端和托管登录域。“传统 Web 应用程序”默认配置带有客户端密钥的授权码授予流程。这是服务器端应用程序的推荐模式。

Part II: Create a Test User

第二部分:创建测试用户

  • Step 01: In the User Pool, click the ▼ Users management tab -> Click Users.

  • Step 02: Click Create user.

    • Invitation message: Send an email invitation.
    • Email address: Use a real email you can access.
    • Temporary password: Generate a password.
  • Step 03: Click Create user.

  • 步骤 01:在用户池中,点击“用户管理”选项卡 -> 点击“用户”。

  • 步骤 02:点击“创建用户”。

    • 邀请消息:发送电子邮件邀请。
    • 电子邮件地址:使用一个你可以访问的真实邮箱。
    • 临时密码:生成一个密码。
  • 步骤 03:点击“创建用户”。

✅ Green banner: User username@example.com has been created successfully. You’ll receive an email with a temporary password. ✅ 绿色横幅:用户 username@example.com 已成功创建。你将收到一封包含临时密码的电子邮件。

⚠️ Don’t log in yet. We’ll do that through the Managed Login in a moment. ⚠️ 先不要登录。我们稍后将通过托管登录进行操作。

Part III: Test with Managed Login (Authorization Code Flow)

第三部分:使用托管登录进行测试(授权码流程)

  • Step 01: View the hosted UI URL: From the ▼ Applications tab -> App clients -> Click View login page.

  • Step 02: Sign in with the user credentials from the email. Cognito will force you to set a permanent password.

  • Step 03: Change password.

  • Step 04: After login, you’ll be redirected to the callback URL.

  • 步骤 01:查看托管 UI URL:从“应用程序”选项卡 -> 应用程序客户端 -> 点击“查看登录页面”。

  • 步骤 02:使用电子邮件中的用户凭证登录。Cognito 将强制你设置永久密码。

  • 步骤 03:更改密码。

  • 步骤 04:登录后,你将被重定向到回调 URL。