【问题标题】:Authorization using Cognito with IAM and Amplify使用 Cognito 与 IAM 和 Amplify 进行授权
【发布时间】:2023-03-27 06:13:02
【问题描述】:

我正在尝试创建一个应用程序,用户可以在其中登录,然后根据他们的角色访问某些 api 资源。

用户被移动到用户池中的组中,每个组都有一个自定义 IAM 角色。

我曾使用放大 CLI 工具来创建身份验证、api 网关和 lambda 函数。 这是在放大中设置的API

? Please select from one of the below mentioned services: REST
? Please select the REST API you would want to update standardApi
? What would you like to do Update path
? Please select the path you would want to edit /std
? Provide a path (e.g., /book/{isbn}): /std
? Choose a Lambda source Use a Lambda function already added in the current Ampl
ify project
? Choose the Lambda function to invoke by this path standardFunction
? Restrict API access Yes
? Restrict access by? Individual Groups
? Select groups: standard
? What kind of access do you want for standard users? create, read, update, dele
te
Successfully updated resource

在控制台中检查时,资源会按预期创建。

问题是在尝试调用 API 时,我收到了 MissingAuthenticationTokenException

这是电话

const apiName = 'standardApi';
const path = '/std';
const myInit = {
    headers: {},
    response: false
};
API.get(apiName, path, myInit)
.then(response => {
    console.log(response);
})
.catch(error => {
    console.log(error.response);
});

我的理解是 Amplify sdk 应该使用正确的身份验证值自动填充请求标头。

如果我尝试手动传递访问令牌,

headers: {
    Authorization: (await Auth.currentSession()).getIdToken().getJwtToken()
},

我收到 IncompleteSignatureException,并显示消息

Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header.

尝试

headers: {
    Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}
},

导致 IncompleteSignatureException 没有消息。

其他帖子建议可能没有正确指定端点,如果我从控制台中的 api 中删除身份验证并重新部署,端点会按预期命中。此外,如果我使用 cognito 用户池创建自定义授权方,则在登录时正确命中端点并传递不记名令牌。

只是 IAM 案例不起作用。

检查 ID 令牌表明正在传入正确的用户名、组和角色。

"cognito:groups": Array [ "standard" ]
"cognito:preferred_role": "arn:aws:iam::************:role/region-*_*********-standardGroupRole"
"cognito:roles": Array [ "arn:aws:iam::************:role/region-*_*********-standardGroupRole"]
"cognito:username": "0a******-****-****-****-************"

使用自动生成的 aws-exports 文件完成 Amplify 配置步骤,该文件包含用户池、身份池和客户端应用程序的正确条目。

【问题讨论】:

标签: amazon-web-services aws-api-gateway amazon-cognito amazon-iam aws-amplify


【解决方案1】:

我知道这可能有点晚了,但我只是想做你想做的事情。

这是我必须做的事情:

  • 在您的 UI 中包含身份验证组件,以便您的 API 调用使用经过身份验证的用户的凭据完成。
  • 请务必在您通过 Cognito 身份验证后执行 API 调用(使用属于您指定组的用户)。
  • 不要包含任何“授权”标头(我查看了代码,发现在设置授权标头时不会生成任何 AWS 签名)。
  • 确保您的 lambda 代码返回 CORS 标头(因此,我遇到了来自 CloudFront 的 InternalServerErrorException)。

执行此操作后,我可以在浏览器的开发者控制台中看到请求已签名,并且具有 API Gateway 所做的 IAM 授权验证所需的所有标头。

我希望这个云对某人有用,因为我花了很多时间才弄明白。

问候, 安德烈斯·拉诺斯

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 2022-01-24
    • 2021-06-05
    • 1970-01-01
    • 2021-07-20
    • 2021-03-19
    • 2019-03-04
    • 2022-11-10
    • 2018-07-30
    相关资源
    最近更新 更多