gpt4 book ai didi

reactjs - 在 React 中使用 aws-amplify 将文件上传到具有联合身份的 S3 时出错

转载 作者:行者123 更新时间:2023-12-04 17:29:02 29 4
gpt4 key购买 nike

当具有 Facebook 联合身份的用户尝试上传图片时,我收到错误消息:AWSS3Provider - 上传错误错误:“请求失败,状态代码为 403”状态码:403 禁止访问

注意到请求中的 URL,当用户使用联合身份 (Facebook) 进行身份验证时,看起来:
请求网址:https://my-gallery-api-dev-photorepos3bucket-XXXX.s3.us-east-2.amazonaws.com/private/undefined/1587639369473-image.jpg?x-id=PutObject

将放置上传图像的文件夹是'undefined',而不是像从 AWS UserPool 验证的用户那样是有效的用户身份,请参阅:
请求网址:https://my-gallery-api-dev-photorepos3bucket-XXXX.s3.us-east-2.amazonaws.com/private/us-east-2%3Aa2991437-264a-4652-a239-XXXXXXXXXXXX/1587636945392-image.jpg?x-id=PutObject

对于身份验证和上传,我正在使用 React aws 依赖项 "aws-amplify": "^3.0.8"

Facebook 身份验证(Facebook 按钮):

async handleResponse(data) {
console.log("FB Response data:", data);
const { userID, accessToken: token, expiresIn } = data;
const expires_at = expiresIn * 1000 + new Date().getTime();
const user = { userID };

this.setState({ isLoading: true });
console.log("User:", user);
try {
const response = await Auth.federatedSignIn(
"facebook",
{ token, expires_at },
user
);
this.setState({ isLoading: false });
console.log("federatedSignIn Response:", response);
this.props.onLogin(response);
} catch (e) {
this.setState({ isLoading: false })
console.log("federatedSignIn Exception:", e);
alert(e.message);
this.handleError(e);
}
}

上传:

import { Storage } from "aws-amplify";

export async function s3Upload(file) {
const filename = `${Date.now()}-${file.name}`;

const stored = await Storage.vault.put(filename, file, {
contentType: file.type
});

return stored.key;
}
     const attachment = this.file
? await s3Upload(this.file)
: null;

我知道 S3 拒绝 403,因为 IAM 角色,我对经过身份验证的用户有:

  # IAM role used for authenticated users
CognitoAuthRole:
Type: AWS::IAM::Role
Properties:
Path: /
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Principal:
Federated: 'cognito-identity.amazonaws.com'
Action:
- 'sts:AssumeRoleWithWebIdentity'
Condition:
StringEquals:
'cognito-identity.amazonaws.com:aud':
Ref: CognitoIdentityPool
'ForAnyValue:StringLike':
'cognito-identity.amazonaws.com:amr': authenticated
Policies:
- PolicyName: 'CognitoAuthorizedPolicy'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Action:
- 'mobileanalytics:PutEvents'
- 'cognito-sync:*'
- 'cognito-identity:*'
Resource: '*'

# Allow users to invoke our API
- Effect: 'Allow'
Action:
- 'execute-api:Invoke'
Resource:
Fn::Join:
- ''
-
- 'arn:aws:execute-api:'
- Ref: AWS::Region
- ':'
- Ref: AWS::AccountId
- ':'
- Ref: ApiGatewayRestApi
- '/*'

# Allow users to upload attachments to their
# folder inside our S3 bucket
- Effect: 'Allow'
Action:
- 's3:*'
Resource:
- Fn::Join:
- ''
-
- Fn::GetAtt: [PhotoRepoS3Bucket, Arn]
- '/private/**${cognito-identity.amazonaws.com:sub}/***'
- Fn::Join:
- ''
-
- Fn::GetAtt: [PhotoRepoS3Bucket, Arn]
- '/private/**${cognito-identity.amazonaws.com:sub}**'

对于在 AWS 用户池中注册的用户(电子邮件、密码),它工作正常,但对于联合用户,AWS 用户池中没有记录,只有在联合身份中,因此不会有 cognito-identity.amazonaws .com:sub 发现那些用户和目录 “未定义” 不属于使用联合身份识别的用户的角色津贴。

请指教:
1. 在哪里/如何修复 URL 中的这个'undefined'
2. 另外,我可能希望将上传 URL 中的 thouse Id 替换为我将在不久的将来添加的用户数据库中生成的用户 Id。如何修复 IAM 角色以使用自定义 ID?

最佳答案

我在执行 Serverless Stack 时遇到了同样的问题教程

当您执行 Extra Credit > React > Facebook Login with Cognito using AWS Amplify 时会出现此错误,正如您所注意到的,如果您通过 Facebook 进行身份验证,则上传文件会失败。

向以下地址发送 PUT 时出现错误:
https://<bucket>.s3.amazonaws.com/private/<identity-id>/<file>
...<identity-id>未定义,因此 PUT 失败。

如果您记录在运行登录命令时得到的结果,您可以追踪这个未定义的来源。例如,当您使用电子邮件和密码登录时,如果您这样做:

await Auth.signIn(fields.email, fields.password);
const currCreds = await Auth.currentCredentials();
console.log('currCreds', currCreds);

...你可以看到 identityId设置正确。

另一方面,当您通过 Auth.federatedSignIn 登录 Facebook 时如果您记录响应,您不会得到 identityId .注意:如果您之前使用电子邮件和密码登录,它将保持不变,因此这种错误配置也会导致上传失败。

我使用的解决方法是添加一个简单的 lambda,它返回 identityId对于已登录的用户,一旦用户使用 facebook 登录,我们就会请求它,我们可以使用 AWS.S3().putObject 将 PUT 发送到正确的 url。

如果你想尝试这个,请考虑你应该在 https 中托管你的 React 应用程序,因为 Facebook 不允许 http 域。您可以设置此添加 HTTPS=true到你的 React .env 文件。

你可以查看我的 repo 协议(protocol)作为例子:
API
Frontend

关于reactjs - 在 React 中使用 aws-amplify 将文件上传到具有联合身份的 S3 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61388515/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com