API Gateway 授权器
实施各种 API Gateway 授权器,包括 Lambda 自定义授权器和 JWT 授权器,实现稳健的身份验证
API Gateway 授权器 是 CoddyKit 上的免费 Serverless Backend with AWS Lambda & API Gateway 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Serverless Backend with AWS Lambda & API Gateway 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
API Gateway Authorizers Intro
Welcome! In this lesson, we'll learn how to secure your serverless APIs using API Gateway Authorizers. These are crucial for controlling who can access your backend services.
Think of an authorizer as a security guard at the entrance of your API. Before any request reaches your Lambda function or other backend service, the authorizer checks the request's credentials.
Why Use API Gateway Authorizers?
Authorizers provide robust authentication and authorization for your APIs. Here's why they are essential:
- Protect Backend Resources: Prevent unauthorized access to your Lambda functions and other services.
- Decouple Auth Logic: Separate authentication logic from your main business logic, keeping your functions cleaner.
- Fine-Grained Access: Control access to specific API methods or resources based on user identity or roles.
Types of Authorizers
API Gateway offers several types of authorizers. Today, we'll focus on the two most flexible and commonly used:
- Lambda Custom Authorizers: A Lambda function you write to perform custom authentication.
- JWT Authorizers: API Gateway's native support for validating JSON Web Tokens (JWTs).
There's also IAM Authorizers, which use AWS IAM roles and policies, but we'll focus on the custom and JWT types here.
Lambda Custom Authorizers Explained
A Lambda Custom Authorizer is a Lambda function that you provide. API Gateway invokes this function with the incoming request's authorization token (e.g., from the Authorization header).
Your Lambda function then processes this token, performs its custom authentication logic (e.g., checks a database, calls an identity provider), and returns an IAM policy.
The Authorization Policy
The core output of your Lambda authorizer is an IAM policy document. This policy tells API Gateway whether to Allow or Deny the request to the target API endpoint.
It includes a principalId (the authenticated user's identifier) and a policyDocument specifying the permissions. If Allow, the request proceeds; if Deny, it's rejected with a 401 Unauthorized error.
Lambda Authorizer Code Example
Here's a simple Python Lambda function acting as an authorizer. It checks for a specific token and returns an 'Allow' or 'Deny' policy based on it.
Try changing the token in the test event to see different outputs!
def lambda_handler(event, context):
token = event.get('authorizationToken')
method_arn = event.get('methodArn')
if token == "my-secret-token-123":
# Allow access
return {
"principalId": "user123",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": method_arn
}
]
}
}
else:
# Deny access
return {
"principalId": "anonymous",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Deny",
"Resource": method_arn
}
]
}
}
# --- Local Test (for demonstration) ---
if __name__ == "__main__":
print("Testing with 'my-secret-token-123':")
event_allow = {
"authorizationToken": "my-secret-token-123",
"methodArn": "arn:aws:execute-api:us-east-1:123456789012:/test/GET/items"
}
print(lambda_handler(event_allow, None))
print("\nTesting with 'invalid-token':")
event_deny = {
"authorizationToken": "invalid-token",
"methodArn": "arn:aws:execute-api:us-east-1:123456789012:/test/GET/items"
}
print(lambda_handler(event_deny, None))JWT Authorizers Explained
JWT (JSON Web Token) Authorizers allow API Gateway to natively validate JWTs. Instead of writing a Lambda function, you configure API Gateway with details about your JWT issuer.
When a request with a JWT comes in, API Gateway automatically performs validation steps like:
- Signature verification
- Expiration checks
- Audience and issuer validation
Configuring a JWT Authorizer
To set up a JWT authorizer, you typically provide API Gateway with:
- Issuer URL: The URL of the identity provider (e.g.,
https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXXfor Cognito). - Audience(s): A list of valid audiences for the token, ensuring the token is intended for your API.
- Identity Source: The header where the JWT is expected (e.g.,
$request.header.Authorization).
API Gateway then uses these details to fetch public keys and validate incoming JWTs.
When to Use Which Authorizer?
Choosing between Lambda and JWT authorizers depends on your needs:
- Lambda Authorizer: Use for highly custom authentication logic, integration with legacy systems, or identity providers not supporting standard OIDC/OAuth2. Offers maximum flexibility.
- JWT Authorizer: Ideal when using standard identity providers like AWS Cognito User Pools, Auth0, Okta, etc. It's simpler to set up and has less operational overhead.
For most modern applications using standard identity providers, JWT authorizers are often the preferred choice.
Authorizer Quick Check
Time for a quick check on what you've learned about API Gateway Authorizers!
Recap: Securing with Authorizers
You've now learned about API Gateway Authorizers, a vital component for securing your serverless APIs!
- Authorizers act as a front-door security check for your API endpoints.
- Lambda Custom Authorizers offer maximum flexibility for custom authentication logic.
- JWT Authorizers provide native, easy-to-configure validation for standard JSON Web Tokens.
By implementing authorizers, you ensure only legitimate requests access your backend services, enhancing the security of your applications.
常见问题解答
「API Gateway 授权器」课时是免费的吗?
是的 — 「API Gateway 授权器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Serverless Backend with AWS Lambda & API Gateway 课程的其余内容,请升级到 CoddyKit PRO。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。
「API Gateway 授权器」这节课中我会学到什么?
实施各种 API Gateway 授权器,包括 Lambda 自定义授权器和 JWT 授权器,实现稳健的身份验证 你通过在浏览器中直接运行的动手代码来练习 Serverless Backend with AWS Lambda & API Gateway,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Serverless Backend with AWS Lambda & API Gateway 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Serverless Backend with AWS Lambda & API Gateway 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「API Gateway 授权器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Serverless Backend with AWS Lambda & API Gateway 课中编写并运行代码吗?
能。每节 Serverless Backend with AWS Lambda & API Gateway 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- IAM 角色与权限
- API Gateway 授权器
- 使用 VPC 保护 Lambda
- 使用 AWS Secrets Manager 保护机密