Vue JS aws-sdk 访问经过身份验证的 Cognito 用户的专用 S3 存储桶

VueJS aws-sdk acces to dedicated S3 bucket for authenticated Cognito user

大家好,我现在转了一天多了,可以找出问题所在。

我需要什么:

  1. 在我的网络应用程序上验证我的用户以控制对存储桶的访问
  2. 只允许每个用户访问我存储桶中的特定文件夹

我做了什么

  1. 使用客户端应用程序和联合池创建 Cognito 用户组
  2. 将我的联合池链接到我的 Cognito 用户组
  3. 使用以下道具创建一个桶

一个。 Public 访问 B.CORS

摄氏度。在 vuejs 中创建一个登录表单并开始使用 AWS-SDK 进行身份验证以进行认知

<script >
import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js'
import * as AWS from 'aws-sdk'
import AwsConfig from '@/config/ConfigAws.js'

export default {
  data () {
    return {
      username: '',
      password: '',
      email: '',
      access_token: null,
      id_token: null,
  
    }
  },
 methods: {

    
    AWS_auth () {
AWS.config.update({ region: AwsConfig.default_region })
var authenticationData = {
        Username: this.email,
        Password: this.password
      }
var userData = {
        Username: this.email,
        Pool: userPool
      }
var poolData = {
        UserPoolId: AwsConfig.cognito_UserPoolId,
        ClientId: AwsConfig.cognito_client_ID
      }
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData)
      var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData)
      cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: (result) => {
          console.log('success auth')
          // isolate acces token
          var accessToken = result.getAccessToken().getJwtToken()
          // isolate id token, id token has to get used for API gateway auth
          var idToken = result.idToken.jwtToken
          // Update AWS config credentials to store credentials for the session
          AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: 'eu-west-1:aaaaaaaaa-XXXXX-4a99-b606-YYYYYYYYYY',
            Logins: { 'cognito-idp.eu-west-1.amazonaws.com/eu-west-1_jjrr8877rL': idToken }
          })
          // store in template data both token
          this.access_token = accessToken
          this.id_token = idToken
          // store in local storage both token, this storage is helpfull at new connexion, to avoir connexion path
          localStorage.labelingAPPAccessToken = accessToken
          localStorage.labelingAPPIdToken = idToken
          this.$store.state.UserAccesToken = localStorage.labelingAPPAccessToken
          // Get COgnito UserData and custom data    
          var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider()
          cognitoidentityserviceprovider.getUser(
            {
              AccessToken: accessToken /* required */
            },
            (err, data, vm) => {
              if (err) {console.log(err,  err.stack)}
              if (data) { console.log('Authentication success') }
              var newdata = data.UserAttributes
              Object.assign(newdata, { IdentityID: String(AWS.config.credentials.identityId) })
              localStorage.setItem('SessionFaaSPlateformStorage4f66b04b5460f2a9d13b', JSON.stringify(newdata))
              this.$store.state.Userdata = newdata
              this.loader_active = false
              this.$router.push('Dashboard/DashboardHome')

              if (err) {
                console.log(err, err.stack)
              }
            }
          )
          console.log('IdentityID')
          console.log(String(AWS.config.credentials.identityId))
        },

        onFailure: function (err) {
          console.log('Auth failed')
          console.log(err, err.stack)
        }
      })
    }
  }
</script >

到目前为止一切顺利,我得到了我需要的一切,我的不同令牌、userId、UserDate 和 AppID

  1. 配置不同的角色和策略以允许用户使用 AWS 服务。 我检索了“plateform_cognito_Role,生成并链接到我的联合用户池,内容如下

一个。信任关系

乙。权限 => 链接到自定义策略

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*",
                "cognito-identity:*"
            ],
            "Resource": [
                "arn:aws:cognito-sync:eu-west-1:454545454545:identitypool/eu-west-1_sssssssss/identity/*/dataset/*",
                "arn:aws:cognito-sync:eu-west-1:454545454545:identitypool/eu-west-1_sssssssss",
                "arn:aws:cognito-sync:eu-west-1:454545454545:identitypool/eu-west-1_sssssssss/identity/*"
            ]
        },
        {
            "Sid": "VisualEditordynamo",
            "Effect": "Allow",
            "Action": [
                "dynamodb:BatchGetItem",
                "dynamodb:PutItem",
                "dynamodb:GetItem",
                "dynamodb:Scan",
                "dynamodb:Query",
                "dynamodb:UpdateItem"
            ],
            "Resource": [
                "arn:aws:dynamodb:eu-west-1:454545454545:table/FaasCloudPlateform_Functions/index/*",
                "arn:aws:dynamodb:eu-west-1:454545454545:table/FaasCloudPlateform_Functions",
                "arn:aws:dynamodb:eu-west-1:454545454545:table/FaasCloudPlateform_Users/index/*",
                "arn:aws:dynamodb:eu-west-1:454545454545:table/FaasCloudPlateform_Users"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::faascloudplatform",
                "arn:aws:s3:::faascloudplatform/*"
            ]
        }
    ]
}

在这个阶段,一切都很顺利,我可以毫无问题地与 dynamo 和 S3 交互。

现在我想隔离每个 Cognito 用户,使其只能访问 bucker 中他自己的特定文件夹

我把之前的政策修改成

{
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::faascloudplatform/Users/${cognito-identity.amazonaws.com:sub}",
                "arn:aws:s3:::faascloudplatform/Users/${cognito-identity.amazonaws.com:sub}/*"
            ]
 }

在我的客户端网络应用程序中进行身份验证时,Identity Id 看起来像“eu-west-1:fec78-0000-36b-80bd-8e1c54ce” 看起来不错, 所以我转到我的 S3 存储,用我的身份 ID 名称创建一个文件夹,并在其中放入一个测试文件。 我的文件的关键是 "Users/eu-west-1:eu-west-1:fec78-0000-36b-80bd-8e1c54ce/avatar.PNG"

回到我的网络应用程序中,我使用 aws-S3 以我之前使用的相同方法查询对象

async function S3getObject (BucketName, KeyName) {
    var params = {
      Bucket: BucketName,
      Key: KeyName
    }
    var s3 = new AWS.S3({
      apiVersion: '2006-03-01'
    })
    const data = (await (s3.getObject(params).promise()))

    return data
  }

剧情来了..... 我得到的承诺 return 作为一个错误

我很挣扎,卡了一段时间

非常感谢您的帮助。

非常感谢

我自己搞定了。 我几乎错过了政策中的一个要素。

我在策略中添加了一个列表对象,现在一切正常

{
            "Sid": "ListYourObjects",
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": [
                "arn:aws:s3:::faascloudplatform"
            ],
            "Condition": {
                "StringLike": {
                    "s3:prefix": [
                        "Users/${cognito-identity.amazonaws.com:sub}"
                    ]
                }
            }
        }