1

我遵循此 AWS API Gateway 文档并使用cognito identity token. 我在控制台中测试了我的 cognito id 令牌API Gateway,它有效:它给了我正确的值,从令牌中正确检索 sub 和 email 值:

测试 id 令牌的工作原理

然后我将 Authorizo​​r 添加到我的方法中:

我的方法请求

但是当我现在测试我的方法时,当我从 API Gateway 中的测试表单(方法内部)发送它们时,所有请求仍然通过(提供或不提供身份令牌):

没有令牌或无效令牌的测试

我本来希望得到“未经授权”或“拒绝访问”的响应,但我得到了 200。我还尝试将方法请求中的“需要 API 密钥”设置为 true 并需要 Autorization 标头,但即便如此,上面的请求也会通过状态 200:

将 API Key Required 设置为 true

我还添加了

"context" : {
        "sub" : "$context.authorizer.claims.sub",
        "email" : "$context.authorizer.claims.email"
}

到我的映射模板,所以完整的模板现在看起来像这样:

{
    "TableName": "myUsersTable",
    "Key": {
        "id": {"S": "$input.params('id')"},
        "username": {"S": "$input.params('id')"}
    },
    
    "context" : {
        "sub" : "$context.authorizer.claims.sub",
        "email" : "$context.authorizer.claims.email"
    }
}

但是 sub 和 email 的日志总是空的(并且响应状态仍然是 200):

Tue Dec 29 10:35:46 UTC 2020 : Endpoint request body after transformations: {
    "TableName": "myUsersTable",
    "Key": {
        "id": {"S": "testUser"},
        "username": {"S": "testUser"}
    },
    
    "context" : {
        "sub" : "",
        "email" : ""
    }
}

我在这里做错了什么?

4

1 回答 1

2

对我来说,当我在 API Gateway 控制台中对其进行测试时,它从未起作用。但是当您使用 Postman 时,它应该可以工作(将 Method Request 中的“API Key Required”设置回 false 并删除需要 Autorization 标头,然后再次部署您的 API 并使用 Postman 对其进行测试,将您的令牌放入请求标头中,例如这:

如何将令牌添加到邮递员

您的 sub 和 email 值的映射模板似乎也正确。我认为当您使用 API Gateway 控制台进行测试时,只是跳过了整个授权验证,但我不确定。请改用 Postman,然后它应该可以工作。

另请参阅:https ://medium.com/@chandupriya93/providing-authorization-to-api-gateway-with-cognito-identity-pools-af451fd3b532

于 2020-12-29T11:34:07.683 回答