安全凭证服务(STS)

STS即Secure Token Service 是一种安全凭证服务,可以使用STS来完成对于临时用户的访问授权。对于跨用户短期访问s3资源时,可以使用STS服务。这样就不需要透露主账号AK/SK,只需要生成一个短期访问凭证给需要的用户使用即可,避免主账号AK/SK泄露带来的安全风险。

初始化STS服务

ak: "<your-access-key>",
sk: "<your-secret-access-key>",
endpoint: "<your-endpoint>", // e.g. http://endpoint or https://endpoint
region: "<your-region>",
	
init: function() {
	let config = {
		accessKeyId: this.ak,
		secretAccessKey: this.sk,
		endpoint: this.endpoint,
		region: this.region,
	};
	this.stsClient = new AWS.STS(config);
},

获取临时token

assumeRole:function () {
	console.log("assumeRole")
	let roleArn = "arn:aws:iam:::role/<your-role>"
	let roleSessionName = "<your-role-session-name>"
	let policy = `{"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":["s3:*"],"Resource":["arn:aws:s3:::<your-bucket>","arn:aws:s3:::<your-bucket>/*"]}}`
	let params = {
		Policy : policy,
		RoleArn : roleArn,
		RoleSessionName : roleSessionName,
        DurationSeconds: 900, // 过期时间
	}
	this.stsClient.assumeRole(params, function(err, data) {
		if (err) {
			console.log("Error", err);
		} else {
			console.log("Success", data);
		}
	});
},

Policy设置例子

允许所有的操作
{"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":["s3:*"],"Resource":["arn:aws:s3:::<your-bucket-name>","arn:aws:s3:::<your-bucket-name>/*"]}}

限制只能上传和下载
{"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":["s3:PutObject","s3:GetObject"],"Resource":["arn:aws:s3:::<your-bucket-name>","arn:aws:s3:::<your-bucket-name>/*"]}}

使用分片上传
{"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":["s3:PutObject","s3:AbortMultipartUpload","s3:ListBucketMultipartUploads","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::<your-bucket-name>","arn:aws:s3:::<your-bucket-name>/*"]}}

其他操作权限
上传权限:s3:PutObject
下载权限:s3:GetObject
删除权限:s3:DeleteObject
获取列表权限:s3:ListBucket

注意:
1.ListObjects 操作是由ListBucket权限控制的
2."Version:2012-10-17"是系统的policy格式的版本号,不能改成其他日期

更多操作权限可以参考:
https://awspolicygen.s3.amazonaws.com/policygen.html
参数 类型 描述
RoleArn String 角色的ARN,在控制台创建角色后可以查看
Policy String 角色的policy,需要是json格式,限制长度1~2048
RoleSessionName String 角色会话名称,此字段为用户自定义,限制长度2~64
DurationSeconds Integer 会话有效期时间,默认为3600s,范围15分钟至12小时

使用临时token

let config = {
	accessKeyId: "<your-access-key>";,
	secretAccessKey: "<your-secret-access-key>",
	sessionToken: "<your-session-token>",
	endpoint: "<your-endpoint>", // e.g. http://endpoint or https://endpoint
};
let s3Client = new AWS.S3(config);