Skip to Content
Cloud Engineering Academy
3. .NET Application Development on AWS

Lab 3.1: an SDK v4 console app with SSO and dependency injection

Build a .NET 10 console app that registers AWS SDK v4 clients through dependency injection, signs in with the learn-sandbox SSO profile, calls STS GetCallerIdentity, lists S3 buckets page by page, and is unit tested with a mocked client.

beginner⏱ 1 h 🟢 FreeDVA-C03

Assumes: .NET 10 LTS · AWSSDK.Extensions.NETCore.Setup 4.1.0.2 · AWSSDK.S3 4.1.1 · AWSSDK.SecurityToken 4.1.0.2 · xunit.v3 4.0.3 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lab you can:

  • Create a .NET 10 console app on the Generic Host and register AWS SDK v4 clients with AddAWSService<T>().
  • Make the SDK use your IAM Identity Center (SSO) profile locally, and explain why the same code needs no change on AWS compute.
  • Call STS GetCallerIdentity to prove which identity the code runs as.
  • List S3 buckets page by page and handle SDK v4's null collections.
  • Unit test AWS-calling code with a mocked client and no AWS account.

Prerequisites

Why this matters in banking

Every .NET service at Harbourline talks to AWS through the SDK. Two habits decide whether that is secure: never using long-lived access keys (the SDK should find temporary credentials from SSO locally and from the role on AWS), and knowing which identity your code is using before it touches data. An engineer who runs a data-fix tool against production while signed in to the wrong account causes an incident. GetCallerIdentity at start-up is a cheap guard rail.

The idea in plain language

The SDK has a credential provider chain: an ordered list of places it looks for credentials. Locally it finds your SSO profile (because you set AWS:Profile or AWS_PROFILE); on ECS, Lambda or EC2 it finds the role of the task, function or instance. Your code just asks for an IAmazonS3 from dependency injection and calls it.

Analogy: the SDK is a courier who checks a fixed list of pockets for a valid pass: first the one you hand over explicitly, then environment variables, then your named profile, then the building's own pass (the role). You never write the pass number on the parcel.

Architecture

Step-by-step

Sign in

aws sso login --profile learn-sandbox
aws sts get-caller-identity --profile learn-sandbox

You should see your account ID and an ARN like arn:aws:sts::<account>:assumed-role/AWSReservedSSO_.../<you>.

Create the solution

mkdir m03-sdk-console && cd m03-sdk-console
dotnet new console -n Harbourline.Tools.BucketReport -o src/Harbourline.Tools.BucketReport
dotnet new console -n Harbourline.Tools.BucketReport.Tests -o tests/Harbourline.Tools.BucketReport.Tests
dotnet new sln --format slnx -n BucketReport
dotnet sln BucketReport.slnx add src/Harbourline.Tools.BucketReport tests/Harbourline.Tools.BucketReport.Tests

Then replace the generated files with the ones below. Add a global.json identical to the labs' (SDK 10.0.100, rollForward: latestFeature, and "test": { "runner": "Microsoft.Testing.Platform" }).

Add the code

Copy the project files, appsettings.json, Program.cs, BucketReport.cs and the test from the Complete code section.

Run it

dotnet run --project src/Harbourline.Tools.BucketReport

Test it

dotnet test --solution BucketReport.slnx

Complete code

src/Harbourline.Tools.BucketReport/Harbourline.Tools.BucketReport.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <RootNamespace>Harbourline.Tools.BucketReport</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.15" />
    <PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.S3" Version="4.1.1" />
    <PackageReference Include="AWSSDK.SecurityToken" Version="4.1.0.2" />
    <!-- Needed at run time for IAM Identity Center (SSO) profiles. Without them the chain skips SSO. -->
    <PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
  </ItemGroup>
  <ItemGroup>
    <None Update="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
    <InternalsVisibleTo Include="Harbourline.Tools.BucketReport.Tests" />
  </ItemGroup>
</Project>
src/Harbourline.Tools.BucketReport/appsettings.json
{
  "AWS": {
    "Profile": "learn-sandbox",
    "Region": "us-east-1"
  },
  "Logging": {
    "LogLevel": { "Default": "Information", "AWSSDK": "Warning" }
  },
  "Report": {
    "ExpectedAccountId": "",
    "PageSize": 50
  }
}
src/Harbourline.Tools.BucketReport/Program.cs
using Amazon.S3;
using Amazon.SecurityToken;
using Harbourline.Tools.BucketReport;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

// Reads the "AWS" section: Profile and Region. On AWS compute leave Profile empty;
// the credential chain then finds the task/function/instance role.
builder.Services.AddDefaultAWSOptions(builder.Configuration.GetAWSOptions());

// One singleton client per service. They are thread-safe and reuse connections.
builder.Services.AddAWSService<IAmazonSecurityTokenService>();
builder.Services.AddAWSService<IAmazonS3>();

builder.Services.Configure<ReportOptions>(builder.Configuration.GetSection("Report"));
builder.Services.AddTransient<BucketReport>();

using var host = builder.Build();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var report = host.Services.GetRequiredService<BucketReport>();
return await report.RunAsync(Console.Out, cts.Token);
src/Harbourline.Tools.BucketReport/BucketReport.cs
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Harbourline.Tools.BucketReport;

public sealed class ReportOptions
{
    /// <summary>If set, the tool refuses to run against any other account (a guard rail).</summary>
    public string? ExpectedAccountId { get; set; }

    public int PageSize { get; set; } = 50;
}

public sealed class BucketReport(
    IAmazonSecurityTokenService sts,
    IAmazonS3 s3,
    IOptions<ReportOptions> options,
    ILogger<BucketReport> log)
{
    public async Task<int> RunAsync(TextWriter output, CancellationToken ct)
    {
        // 1. Who am I? Never act before you know.
        var me = await sts.GetCallerIdentityAsync(new GetCallerIdentityRequest(), ct);
        output.WriteLine($"Account : {me.Account}");
        output.WriteLine($"Identity: {me.Arn}");

        var expected = options.Value.ExpectedAccountId;
        if (!string.IsNullOrWhiteSpace(expected) && expected != me.Account)
        {
            log.LogError("Refusing to run: signed in to {Actual}, expected {Expected}", me.Account, expected);
            return 3;
        }

        // 2. List buckets page by page (ListBuckets supports MaxBuckets + ContinuationToken).
        var total = 0;
        string? token = null;
        do
        {
            var page = await s3.ListBucketsAsync(new ListBucketsRequest
            {
                MaxBuckets = options.Value.PageSize,
                ContinuationToken = token,
                BucketRegion = null, // all Regions
            }, ct);

            // SDK v4: collections are null (not empty) when the service returns none.
            foreach (var bucket in page.Buckets ?? [])
            {
                output.WriteLine($"  {bucket.BucketName,-63} {bucket.BucketRegion ?? "?",-12} {bucket.CreationDate:yyyy-MM-dd}");
                total++;
            }
            token = page.ContinuationToken;
        }
        while (!string.IsNullOrEmpty(token));

        output.WriteLine($"{total} bucket(s).");
        return 0;
    }
}
tests/Harbourline.Tools.BucketReport.Tests/Harbourline.Tools.BucketReport.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <IsPackable>false</IsPackable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="xunit.v3" Version="4.0.3" />
    <PackageReference Include="NSubstitute" Version="6.2.0" />
  </ItemGroup>
  <ItemGroup>
    <Using Include="Xunit" />
    <ProjectReference Include="..\..\src\Harbourline.Tools.BucketReport\Harbourline.Tools.BucketReport.csproj" />
  </ItemGroup>
</Project>
tests/Harbourline.Tools.BucketReport.Tests/BucketReportTests.cs
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using Harbourline.Tools.BucketReport;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;

public class BucketReportTests
{
    private static CancellationToken Ct => TestContext.Current.CancellationToken;

    private static IAmazonSecurityTokenService Sts(string account)
    {
        var sts = Substitute.For<IAmazonSecurityTokenService>();
        sts.GetCallerIdentityAsync(Arg.Any<GetCallerIdentityRequest>(), Arg.Any<CancellationToken>())
           .Returns(new GetCallerIdentityResponse { Account = account, Arn = $"arn:aws:sts::{account}:assumed-role/Dev/learner" });
        return sts;
    }

    [Fact]
    public async Task Follows_continuation_tokens_and_tolerates_null_pages()
    {
        var s3 = Substitute.For<IAmazonS3>();
        s3.ListBucketsAsync(Arg.Is<ListBucketsRequest>(r => r.ContinuationToken == null), Arg.Any<CancellationToken>())
          .Returns(new ListBucketsResponse
          {
              Buckets = [new S3Bucket { BucketName = "hl-m03-a", BucketRegion = "us-east-1" }],
              ContinuationToken = "page-2",
          });
        s3.ListBucketsAsync(Arg.Is<ListBucketsRequest>(r => r.ContinuationToken == "page-2"), Arg.Any<CancellationToken>())
          .Returns(new ListBucketsResponse { Buckets = null, ContinuationToken = null }); // v4 null collection

        var output = new StringWriter();
        var exit = await new BucketReport(Sts("111122223333"), s3, Options.Create(new ReportOptions()), NullLogger<BucketReport>.Instance)
            .RunAsync(output, Ct);

        Assert.Equal(0, exit);
        Assert.Contains("hl-m03-a", output.ToString());
        Assert.Contains("1 bucket(s).", output.ToString());
        await s3.Received(2).ListBucketsAsync(Arg.Any<ListBucketsRequest>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Refuses_to_run_in_an_unexpected_account()
    {
        var s3 = Substitute.For<IAmazonS3>();
        var exit = await new BucketReport(Sts("999999999999"), s3,
                Options.Create(new ReportOptions { ExpectedAccountId = "111122223333" }), NullLogger<BucketReport>.Instance)
            .RunAsync(new StringWriter(), Ct);

        Assert.Equal(3, exit);
        await s3.DidNotReceive().ListBucketsAsync(Arg.Any<ListBucketsRequest>(), Arg.Any<CancellationToken>());
    }
}

Code explained

  1. Host.CreateApplicationBuilder (namespace Microsoft.Extensions.Hosting, which console projects do not import implicitly) — the same configuration, logging and DI as ASP.NET Core, without a web server.
  2. GetAWSOptions() — reads AWS:Profile and AWS:Region. AWS_PROFILE/AWS_REGION environment variables (or AWS__Profile) override it, as with any .NET configuration.
  3. AddAWSService<T>() — registers a singleton client created with those options. Clients are expensive to create and safe to share.
  4. AWSSDK.SSO and AWSSDK.SSOOIDC — the SSO credential provider loads these assemblies at run time. Without them, the chain silently skips your SSO profile and you get a "no credentials" error.
  5. GetCallerIdentityAsync — needs no IAM permission; it always works for valid credentials. That makes it the perfect first call.
  6. ExpectedAccountId — an explicit guard. Exit code 3 lets scripts detect the refusal.
  7. MaxBuckets + ContinuationToken — S3 ListBuckets is paginated; accounts with many buckets would otherwise be truncated. BucketRegion filters by Region when set.
  8. page.Buckets ?? [] — in SDK v4 list properties are null when absent. Code written for v3 (which returned empty lists) throws NullReferenceException.
  9. The tests mock IAmazonS3 and IAmazonSecurityTokenService with NSubstitute: no network, no account, and they prove pagination, null handling and the guard rail.

Expected output

Account : 123456789012
Identity: arn:aws:sts::123456789012:assumed-role/AWSReservedSSO_LearnSandboxAdmin_0123456789abcdef/learner
  cdk-hnb659fds-assets-123456789012-us-east-1                      us-east-1    2026-11-02
0 bucket(s).

(The count line reads 1 bucket(s). if the CDK bootstrap bucket exists, or 0 bucket(s). in a fresh account.) Tests: total: 2, failed: 0, succeeded: 2.

Security considerations

⚠ Learning shortcut — not for production

AWS:Profile in appsettings.json is convenient on your laptop. Deployed code must not name a profile: remove it (or override it with an empty value) so the SDK uses the role of the ECS task, Lambda function or EC2 instance. Never put access keys in configuration, environment variables of shared machines, or source control.

  • ListBuckets reveals bucket names, which can themselves be sensitive (customer or project names). Treat the output as internal.
  • The SSO token cache in ~/.aws/sso/cache is a credential. Lock your workstation and let sessions expire.

Troubleshooting

SymptomLikely causeFix
Unable to get IAM security credentials from EC2 Instance Metadata Service or "no credentials"Profile not found, or SSO packages missing so the chain fell through to IMDSCheck AWS:Profile; add AWSSDK.SSO and AWSSDK.SSOOIDC
The SSO session associated with this profile has expiredSSO token older than the session durationaws sso login --profile learn-sandbox
AccessDenied on ListBucketsPermission set lacks s3:ListAllMyBucketsUse a permission set that allows it, or run only the STS part
Wrong Region errorsAWS:Region missing and no default in the profileSet AWS:Region or AWS_REGION
NullReferenceException in the loopv3-style code iterating page.Buckets directly?? []
Test project runs zero testsglobal.json missing the MTP runner, or OutputType not ExeCopy global.json from a lab; check the csproj

Cost and cleanup

Free: STS GetCallerIdentity has no charge and ListBuckets requests cost a fraction of a cent. Nothing is created, so there is nothing to tear down. Run aws sso logout when you finish for the day.

Exercises

  • 🟢 Guided: Run the tool with AWS_PROFILE=does-not-exist and read the error. Then set Report:ExpectedAccountId to a wrong value and confirm exit code 3.
  • 🟡 Challenge: Add a --region filter using BucketRegion and a test proving it is passed to the request.
  • 🔴 Live problem: A colleague's copy of this tool works on their laptop but fails in a Fargate task with "The config profile (learn-sandbox) could not be found". Explain and fix without changing code.

Solutions

Knowledge check

Certification practice

Completion checklist

  • The tool printed my account and role ARN
  • Both unit tests pass without AWS access
  • I can explain why AWSSDK.SSO and AWSSDK.SSOOIDC are needed
  • I can explain what changes (and what doesn't) on AWS compute

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page