安全凭证服务(STS)

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

初始化STS服务

Aws::String ak = "<your-access-key>";
Aws::String sk = "<your-secret-access-key>";
Aws::String endPoint = "<your-endpoint>";

Aws::Auth::AWSCredentials cred(ak, sk);
Aws::Client::ClientConfiguration cfg;
cfg.endpointOverride = endPoint;
cfg.scheme = Aws::Http::Scheme::HTTP;
cfg.verifySSL = false;
sts_client = new Aws::STS::STSClient(cred, cfg);

获取临时token

const Aws::String roleArn = "arn:aws:iam:::role/xxxxxx";
const Aws::String roleSessionName = "<your-session-name>";
const Aws::String bucket_name = "<your-bucket-name>";
const Aws::String policy = "{\"Version\":\"2012-10-17\","
	"\"Statement\":" 
	"{\"Effect\":\"Allow\","
	"\"Action\":[\"s3:*\"]," // 允许进行 S3 的所有操作。如果仅需要上传,这里可以设置为 PutObject
	"\"Resource\":[\"arn:aws:s3:::" + bucket_name + "\",\"arn:aws:s3:::" + bucket_name + "/*\"]"// 允许操作默认桶中的所有文件,可以修改此处来保证操作的文件
	"}}";
Aws::STS::Model::AssumeRoleRequest request;
request.SetPolicy(policy);
request.SetRoleArn(roleArn);
request.SetRoleSessionName(roleSessionName);
std::cout << "policy:" << policy << std::endl;
Aws::STS::Model::AssumeRoleOutcome outcome = sts_client->AssumeRole(request);
if (outcome.IsSuccess())
{
	auto& cred = outcome.GetResult().GetCredentials();
	std::cout << "ak:" << cred.GetAccessKeyId() << std::endl;
	std::cout << "sk:" << cred.GetSecretAccessKey() << std::endl;
	std::cout << "token:" << cred.GetSessionToken() << std::endl;
	return true;
}
else
{
	auto err = outcome.GetError();
	std::cout << "Error: AssumeRole: " <<
		err.GetExceptionName() << ", " << err.GetMessage() << std::endl;
	return false;
}
参数 类型 描述
RoleArn String 角色的ARN,在控制台创建角色后可以查看
Policy String 角色的policy,需要是json格式
RoleSessionName String 角色会话名称
DurationSeconds Integer 会话有效期时间,默认为3600s