Access AWS from Asp.Net Core 2

Today when you start developing an application in any framework, including Asp.Net Core 2, Amazon Web Services (AWS) is an inevitable choice for a lot of reasons, like, multiple database technologies (relational and NoSQL), serverless options (AWS Lambda), CI/CD options (like ElasticBeanstalk & Containers) and many many more services of any type for any problem.

To connect to AWS from Asp.Net Core 2 application we need to create IAM user that has programmatic access to the platform.
After logging to AWS console using root user, we can go to Service -> Security, Identity & Compliance -> IAM -> Users – Add User.

Adding a user is a 4 steps process where we have to define type of access and permissions for services and actions that is allowed to perform.

First step: write user name or names if you want to more than one in same step

Second step: we’re have the option to attach policy(ies) to the user, that means what user is allowed to do / actions to perform
Third step: review actions, number of users we are adding and policies we’ll attach to them
Fourth step: user is created and we’re presented with user credentials, access key and secret key

After downloading access credentials (Access Key and Secret Key) there are multiple ways how to use them in an Asp.Net Core 2 application.

Here I will cover a quick way that I use in development environment, that’s app settings json file.

In appsettings.json file create a section with aws credential details, like below:

"AwsAccessInfo": {
    "Username": "aws-prog-usr",
    "Region":  "us-east-1", 
    "AccessKey": "AKIAIT7HUY********",
    "SecretKey": "K54At3EAJTx******C7Jnv5YYB*****zp+xIO"

We retrieve configuration from json file to register in the system using dependency injection mechanism of the framework, and Startup.cs file ConfigureServices method looks like below:

        public void ConfigureServices(IServiceCollection services)


And now it’s ready and accessible within any controller. A sample of constructor method on home controller, where you can instantiate AWS Client and/or DynamoDB Context helper classes to access AWS resources, would look like this:

 public HomeController(IOptions<AwsAccessInfo> awsAccessInfoOptions)
            var awsAccessInfo = awsAccessInfoOptions.Value;
            var credentials = new BasicAWSCredentials(awsAccessInfo.AccessKey, awsAccessInfo.SecretKey);
            var client = new AmazonDynamoDBClient(credentials, RegionEndpoint.GetBySystemName(awsAccessInfo.Region));
            _dynamoDbContext = new DynamoDBContext(client);

This method is very usable for development. For production you can generate new access details (AWS Access & Secret Key) and create .production appsettings file.

Leave a Reply

Your email address will not be published. Required fields are marked *