我有一个带有 API 网关的 lambda 函数,具有多个路由。它工作得很好,但我想限制仅限我公司内的用户访问。
目前我可以从浏览器访问API
https://gg5ereew0.execute-api.us-east-1.amazonaws.com/test/pets
这允许我不想要的公共访问。 根据AWS文档这里,有多种方法可以限制对API的访问,但我不确定哪一种是最容易实现的。
MyApiGateway:
Type: AWS::Serverless::Api
Properties:
Name:
!Sub
- '${TheEnv}-${TheAppNameForResources}-api'
- TheEnv: !Ref Environment
TheAppNameForResources: !Ref AppNameForResources
TheBucketRegion: !Ref AWS::Region
TracingEnabled: true
OpenApiVersion: 3.0.2
Cors:
AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
AllowMethods: "'*'"
AllowOrigin: "'*'"
StageName: test
Auth:
ResourcePolicy:
CustomStatements:
- Effect: Allow
Principal: "*"
Action: "execute-api:Invoke"
Resource: "execute-api:us-east-1:xxxxxxx4:qkmigyu020/test/GET/pets"
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Description: >
Currently does not support S3 upload event.
Handler: app.lambda_handler
Runtime: python3.12
FunctionName:
!Sub
- "${TheEnv}-${TheAppNameForResources}-get-v1"
- TheEnv: !Ref Environment
TheAppNameForResources: !Ref AppNameForResources
CodeUri: .
MemorySize: 10240
Role: !GetAtt MyLambdaExecutionRole.Arn
Events:
MyPaymentAPIEvent:
Type: Api
Properties:
RestApiId:
Ref: MyApiGateway
Path: /pets
Method: GET
MyLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName:
!Sub
- "${TheAppNameForResources}-${TheEnvName}-lambda-execution-role"
- TheAppNameForResources: !Ref AppNameForResources
TheEnvName: !Ref Environment
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: ['lambda.amazonaws.com', 'apigateway.amazonaws.com']
Action: ['sts:AssumeRole']
Policies:
- PolicyName:
!Sub
- "${TheAppNameForResources}-${TheEnvName}-lambda-execution-role-policy"
- TheAppNameForResources: !Ref AppNameForResources
TheEnvName: !Ref Environment
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
- 'batch:SubmitJob'
- 'batch:DescribeJobs'
- 'batch:CancelJob'
- 'apiGateway:Invoke'
- 'S3:*'
我有点困惑我到底应该在哪里限制 API 访问。
任何帮助理解这一点的帮助都非常感谢。
可能会通过某种方式“限制”用户的访问。我将限制放在引号之间,因为您并不 100% 清楚限制的含义。无论如何,我想到以下内容:
如果您想要基于用户的访问,请使用用户身份验证。如果您不关心用户但只接受提供访问密钥的用户,请使用访问密钥。还要考虑到访问密钥不是身份验证。因此,潜在的解决方案可能取决于您的特定用例和要求。