如何使用Amazon Cognito进行未经认证的访问?

如何使用Amazon Cognito进行未经认证的访问?

问题描述:

  1. 我创建联合身份
  2. 启用身份验证的访问将其与复选框
  3. 创建的角色与此身份相关联,并给它管理员访问,所以它应该具有的所有权限
  4. 然后我添加此代码将文件上传到AWS S3,它可以与Access/Secret密钥一起使用,但我不想将其暴露给UI,但它不适用于Cognito

要清楚,一切都是客户端JavaScript,我希望无服务器的一切,所以我没有自己的API,也不会在我的终端实现自定义访问提供程序。我只想防止在UI中暴露我的访问权限和密钥。如何使用Amazon Cognito进行未经认证的访问?

/** 
    * Handle file upload with Amazon S3 bucket 
    * @param id - record ID in local DB 
    * @param doc - file to be uploaded, taken from event.target.files 
    * @param done - callback to call after upload 
    */ 
    public sendFileToAws(id: number, doc: File, done: Function) { 

    // @Todo : Move to config 

    let pointer = this; 

    aws.config.region = pointer.awsRegion; 
    aws.config.credentials = new aws.CognitoIdentityCredentials({ 
     IdentityPoolId: 'us-east-1:e48af67b-c315-47ca-b816-000000000000', 
     RoleArn: 'arn:aws:iam::000000000000:role/GognitoSuperUserRole', 
     AccountId: '000000000000' 
    }); 

    //aws.config.update({ 
    // region: pointer.awsRegion, 
    // accessKeyId: pointer.awsAccessKey, 
    // secretAccessKey: pointer.awsSecretKey 
    //}); 

    let server = new aws.S3({ params: { Bucket: pointer.awsStorageName } }); 
    let directory = pointer.getDocumentDirectory() + '/' + id + '-' + doc.name; 

    let params = { 
     Key: directory, 
     ContentType: doc.type, 
     Body: doc, 
     Bucket: pointer.awsStorageName, 
     ACL: pointer.awsPermission 
    }; 

    server.upload(params, (e, data) => { 
     done(e, data); 
    }); 
    } 

它返回我下面的错误:

<ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"> 
    <Error> 
    <Type>Sender</Type> 
    <Code>AccessDenied</Code> 
    <Message>Not authorized to perform sts:AssumeRoleWithWebIdentity</Message> 
    </Error> 
    <RequestId>28b768a5-8f30-11e7-a7bf-4b5038235cb8</RequestId> 
</ErrorResponse> 

我也正在同时使用认证和未认证的Cognito身份前端打字稿应用。

未经身份验证的身份,我的流程是这样的:

  • 创建使用CognitoIdentity.getId()身份池一个新的身份。
  • 仅使用身份池ID和新身份标识创建凭证对象。

该代码看起来是这样的:

var cognitoidentity = new AWS.CognitoIdentity(); 
var params = { 
    IdentityPoolId: 'us-east-1:bxxxxxx-cxxx-4xxx-8xxx-9xxxxxxxxxxx' 
}; 

// tslint:disable-next-line:no-any 
cognitoidentity.getId(params, function(err: any, data: any) { 
    if (err) { 
     console.log(err, err.stack); // an error occurred 
    } else { 

     AWS.config.credentials = new AWS.CognitoIdentityCredentials({ 
      IdentityPoolId: 'us-east-1:bxxxxxxx-cxxx-4xxx-8xxx-9xxxxxxxxxxx', 
      IdentityId: data.IdentityId 
     }); 

     // access AWS resources 
    } 
}); 

这将导致你的应用程序获得临时IAM凭证用于访问后端资源(访问密钥,密钥,会话令牌)。

作用假设当你使用这些按键会在你的身份池设置配置的作用:

enter image description here

这样你就不必在IAM角色名暴露给浏览器,无论是。 AWS将根据IAM密钥简单地承担正确的角色。

快乐黑客!