安全凭证服务(STS)

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

初始化STS服务

private const string AK = "<your-access-key>";
private const string SK = "<your-secret-access-key>";
private const string ENDPOINT = "<your-endpoint>"; // e.g. http://endpoint or https://endpoint
private readonly AmazonSecurityTokenServiceClient stsClient;

public S3ClientToCtyun()
{
	var credentials = new BasicAWSCredentials(AK, SK);
	var confSts = new AmazonSecurityTokenServiceConfig
	{
		ServiceURL = ENDPOINT
	};
	this.stsClient = new AmazonSecurityTokenServiceClient(credentials, confSts);
}

获取临时token

public void AssumeRole()
{
	var bucket = "<your-bucket-name>";
	var roleSessionName = "<your-session-name>";
	var roleArn = "arn:aws:iam:::role/xxxxxx";
	var policy = "{\"Version\":\"2012-10-17\"," + "\"Statement\":" + "{\"Effect\":\"Allow\","
	+ "\"Action\":[\"s3:*\"]," // 允许进行 S3 的所有操作。如果仅需要上传,这里可以设置为 PutObject
	+ "\"Resource\":[\"arn:aws:s3:::" + bucket + "\",\"arn:aws:s3:::" + bucket + "/*\"]"// 允许操作默认桶中的所有文件,可以修改此处来保证操作的文件
	+ "}}";

	AssumeRoleRequest req = new AssumeRoleRequest();
	req.Policy = policy;
	req.RoleArn = roleArn;
	req.RoleSessionName = roleSessionName;
	var task = this.stsClient.AssumeRoleAsync(req);
	try
	{
		var result = task.Result;
		Console.Out.WriteLine("AssumeRole, ak={0}, sk={1}, token={2}", result.Credentials.AccessKeyId, 
			result.Credentials.SecretAccessKey, result.Credentials.SessionToken);
	}
	catch (Exception ex)
	{
		Console.Out.WriteLine("exception: {0}", ex.Message);
	}
}
参数 类型 描述
RoleArn String 角色的ARN,在控制台创建角色后可以查看
Policy String 角色的policy,需要是json格式,限制长度1~2048
RoleSessionName String 角色会话名称,此字段为用户自定义,限制长度2~64
DurationSeconds Integer 会话有效期时间,默认为3600s

使用临时token

实现一个CredentialsProvider,支持更新ak/sk和token。

public class MyCredProvider : AWSCredentials
{
	private readonly object syncRoot = new object();
	private ImmutableCredentials creds;

	public MyCredProvider(string ak, string sk, string token)
	{
		creds = new ImmutableCredentials(ak, sk, token);
	}

	public override ImmutableCredentials GetCredentials()
	{
		lock (syncRoot)
		{
			return creds.Copy();
		}
	}

	// 更新token
	public void UpdateCred(string ak, string sk, string token)
	{
		lock (syncRoot)
		{
			creds = new ImmutableCredentials(ak, sk, token);
		}
	}
}

使用临时token

var ak = "<your-access-key>";
var sk = "<your-secret-access-key>";
var endPoint = "<your-endpoint>"; // e.g. http://endpoint or https://endpoint
var token = "<your-session-token>";            
var credentials = new MyCredProvider(ak, sk, token);
var conf = new AmazonS3Config
{
	ServiceURL = endPoint
};
AmazonS3Client s3 = new AmazonS3Client(credentials, conf);