如何为单个HttpApi事件禁用全局配置的ExampleAuthoriser授权器
解决AWS SAM中HttpApi全局授权器下单个端点免认证的问题
要在不拆分API的前提下,实现全局配置授权器但指定单个端点免认证,你可以按以下方式修改SAM配置:
1. 为HttpApi设置全局默认授权器
在AWS::Serverless::HttpApi的Auth配置中添加DefaultAuthorizer,让所有端点默认关联你的ExampleAuthoriser:
ExampleApi: Type: AWS::Serverless::HttpApi Properties: FailOnWarnings: True Auth: DefaultAuthorizer: ExampleAuthoriser # 全局默认使用该授权器 Authorizers: ExampleAuthoriser: JwtConfiguration: issuer: !FindInMap [AccountMap, !Ref "AWS::AccountId", IssuerUrl] CorsConfiguration: AllowOrigins: - !FindInMap [AccountMap, !Ref "AWS::AccountId", CorsAllowOrigins] AllowHeaders: - "*" AllowMethods: - POST MaxAge: 0
2. 为目标端点指定免认证配置
在ExamplePostApi的事件配置中,通过Auth属性显式指定授权器为NONE,覆盖全局默认规则:
ExampleService: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: dotnet6 # 修正原配置的拼写错误 Timeout: 30 MemorySize: 1024 Events: ExampleGetApi: Type: HttpApi Properties: ApiId: !Ref ExampleApi Path: /get Method: POST ExamplePostApi: Type: HttpApi Properties: ApiId: !Ref ExampleApi Path: /post Method: POST Auth: Authorizer: NONE # 该端点跳过授权验证
关键说明
- 全局默认授权器的设置会让所有未单独配置Auth的端点自动使用ExampleAuthoriser;
Authorizer: NONE是SAM支持的特殊值,用于明确指定该端点不需要任何授权验证;- 修正了原配置中
Runtime的拼写错误(dotnt6改为dotnet6),避免部署时出现运行环境识别错误。
内容的提问来源于stack exchange,提问作者Hughesey
相关产品推荐
相关产品推荐

