Amazon S3, or Amazon Simple Storage Service, is an AWS cloud object storage service. It allows you to scale, secure, and manage your data efficiently. More than that, you can use it even if you host your application elsewhere (Azure, Google Cloud, etc.).
Installation
First, you have to add libraries to your project. AWSSDK.S3 and AWSSDK.Extensions.NETCore.Setup.
dotnet add package AWSSDK.S3
dotnet add AWSSDK.Extensions.NETCore.Setup
Add AwsOptions
To add AWS configuration, we will use an option pattern. You have to create a non-abstract class with the public constructor.
public class AwsOptions {
public const string SectionName = "AWS";
public string BucketName { get; set; } = string.Empty;
public string Environment { get; set; } = string.Empty;
public string AccessKey { get; set; } = string.Empty;
public string SecretKey { get; set; } = string.Empty;
}
Then, go to your appsettings file and add a section for AWS. It's essential to keep the same names of properties.
"AWS": {
"BucketName": "your_bucket_name",
"Environment": "your_environment",
"AccessKey": "<secret>",
"SecretKey": "<secret>"
}
Finally, go to the Program.cs and add options and services.
var options = builder.Configuration.GetSection(AwsOptions.SectionName).Get<AwsOptions>();
ArgumentNullException.ThrowIfNull(options);
var awsOptions = builder.Configuration.GetAWSOptions();
awsOptions.Credentials = new BasicAWSCredentials(options.AccessKey, options.SecretKey);
// Choose your region from AWS
awsOptions.Region = RegionEndpoint.EUNorth1;
builder.Services.AddDefaultAWSOptions(awsOptions);
builder.Services.AddAWSService<IAmazonS3>();
Get an Access and a Secret Key from AWS S3
User creation
In AWS go to IAM.
Choose "Users" from "Access management".
Click "Create user".
Input the name and click "Next".
Set permissions. Amazon recommends using groups. Click "Create group".
Search for policy for S3 and choose what you need. Name the user group and click "Create user group".
After group creation, choose it from the table and click "Next".
Then you will see the summary page. If everything is okay, click "Create user".
Get keys
Click your user name.
Navigate to "Security credentials".
Go to "Access keys" and click "Create access key".
Choose a use case. For that case, you should choose "Application running outside AWS".
Setting the description tag is optional. Click "Create access key".
Save your access key and secret access key.
.Net Secret Manager
To keep your secrets locally, we will use .Net Secret Manager. In your project directory use the console:
dotnet user-secrets init
dotnet user-secrets set "AWS:AccessKey" "YourAccessKey"
dotnet user-secrets set "AWS:SecretKey" "YourSecretKey"
Protip
Remarks
You can find the full code example here
If you have any questions you can ask me:
contact@chihuahuacoder.com