Creating a C# application to view folders and files that are stored in AWS S3 for clients that sign up to my site.
Currently I can create a IAM user and assign it permission to a specific folder. But ran into issues when I am trying to view the folder and its contents. I can view the folder if I use the AWS access key and secret key but was wondering if there is a user level credential that I can use to retrieve the folders the user has been given permission to?
This is what I have got so far.
Policy pl = GeneratePolicy(bucketName, foldername);
Credentials creds = GetFederatedCredentials(pl, username);
var sessionCredentials = new SessionAWSCredentials(creds.AccessKeyId, creds.SecretAccessKey, creds.SessionToken);
using (var client = new AmazonS3Client(sessionCredentials, Amazon.RegionEndpoint.USEast1))
{
var response = client.ListObjects(request);
foreach (var subFolder in response.CommonPrefixes)
{
/* list the sub-folders */
Console.WriteLine(subFolder);
}
foreach (var file in response.S3Objects)
{
/* list the files */
}
}
But getting an error on client.ListObjects(request) - access denied error
Here is the GeneratePolicy code
public static Policy GeneratePolicy(string bucket, string username)
{
var statement = new Statement(Statement.StatementEffect.Allow);
// Allow access to the sub folder represented by the username in the bucket
statement.Resources.Add(ResourceFactory.NewS3ObjectResource(bucket, username + "/*"));
// Allow Get and Put object requests.
statement.Actions = new List<ActionIdentifier>() { S3ActionIdentifiers.GetObject, S3ActionIdentifiers.PutObject };
// Lock the requests coming from the client machine.
//statement.Conditions.Add(ConditionFactory.NewIpAddressCondition(ipAddress));
var policy = new Policy();
policy.Statements.Add(statement);
return policy;
}
Here is the GetFederatedCredentials code
public static Credentials GetFederatedCredentials(Policy policy, string username)
{
var request = new GetFederationTokenRequest()
{
Name = username,
Policy = policy.ToJson()
};
var stsClient = new AmazonSecurityTokenServiceClient(AWS_ACCESS_KEY, AWS_SECRET_KEY, Amazon.RegionEndpoint.USEast1);
var response = stsClient.GetFederationToken(request);
return response.GetFederationTokenResult.Credentials;
}
Any help would be greatly appreciated. Thanks in advance
Aucun commentaire:
Enregistrer un commentaire