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.
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
GetCallerIdentityto 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
- AWS SDK for .NET v4 in depth and AWS clients and dependency injection
- Module 0: Orientation — AWS CLI v2 with the
learn-sandboxSSO profile configured - .NET 10 SDK (or Docker with
mcr.microsoft.com/dotnet/sdk:10.0)
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-sandboxYou 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.TestsThen 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.BucketReportTest it
dotnet test --solution BucketReport.slnxComplete code
<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>{
"AWS": {
"Profile": "learn-sandbox",
"Region": "us-east-1"
},
"Logging": {
"LogLevel": { "Default": "Information", "AWSSDK": "Warning" }
},
"Report": {
"ExpectedAccountId": "",
"PageSize": 50
}
}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);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;
}
}<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>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
Host.CreateApplicationBuilder(namespaceMicrosoft.Extensions.Hosting, which console projects do not import implicitly) — the same configuration, logging and DI as ASP.NET Core, without a web server.GetAWSOptions()— readsAWS:ProfileandAWS:Region.AWS_PROFILE/AWS_REGIONenvironment variables (orAWS__Profile) override it, as with any .NET configuration.AddAWSService<T>()— registers a singleton client created with those options. Clients are expensive to create and safe to share.AWSSDK.SSOandAWSSDK.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.GetCallerIdentityAsync— needs no IAM permission; it always works for valid credentials. That makes it the perfect first call.ExpectedAccountId— an explicit guard. Exit code 3 lets scripts detect the refusal.MaxBuckets+ContinuationToken— S3ListBucketsis paginated; accounts with many buckets would otherwise be truncated.BucketRegionfilters by Region when set.page.Buckets ?? []— in SDK v4 list properties are null when absent. Code written for v3 (which returned empty lists) throwsNullReferenceException.- The tests mock
IAmazonS3andIAmazonSecurityTokenServicewith 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.
ListBucketsreveals bucket names, which can themselves be sensitive (customer or project names). Treat the output as internal.- The SSO token cache in
~/.aws/sso/cacheis a credential. Lock your workstation and let sessions expire.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
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 IMDS | Check AWS:Profile; add AWSSDK.SSO and AWSSDK.SSOOIDC |
The SSO session associated with this profile has expired | SSO token older than the session duration | aws sso login --profile learn-sandbox |
AccessDenied on ListBuckets | Permission set lacks s3:ListAllMyBuckets | Use a permission set that allows it, or run only the STS part |
| Wrong Region errors | AWS:Region missing and no default in the profile | Set AWS:Region or AWS_REGION |
NullReferenceException in the loop | v3-style code iterating page.Buckets directly | ?? [] |
| Test project runs zero tests | global.json missing the MTP runner, or OutputType not Exe | Copy 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-existand read the error. Then setReport:ExpectedAccountIdto a wrong value and confirm exit code 3. - 🟡 Challenge: Add a
--regionfilter usingBucketRegionand 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
With a missing profile the SDK throws an AmazonClientException saying the profile could not be found: environment variables override appsettings.json, so AWS_PROFILE wins. With a wrong ExpectedAccountId, the tool prints the identity, logs "Refusing to run" and exits with 3 (check with echo $?). The guard runs after GetCallerIdentity and before any data access, which is the point.
Add public string? Region { get; set; } to ReportOptions, bind it from Report:Region (command-line --Report:Region us-east-1 works with the host's configuration), and set BucketRegion = options.Value.Region. Test: Arg.Is<ListBucketsRequest>(r => r.BucketRegion == "eu-west-2") on the mock, and assert it was received once.
appsettings.json names a profile, and there are no profiles in a container. Override it with an environment variable in the task definition: AWS__Profile set to an empty string, or better, remove the profile from appsettings.json and put it in appsettings.Development.json or AWS_PROFILE on the laptop only. The SDK then uses the task role. Also make sure the task role has s3:ListAllMyBuckets.
Knowledge check
Answer: It needs no permissions, confirms the credentials work, and tells you which account and role you are about to act as, so you can refuse to continue in the wrong account.
Answer: Only configuration: no profile is set, so the credential chain finds the ECS task role's temporary credentials. The code is identical.
Certification practice
A developer needs to run a .NET tool locally against a sandbox account. The company uses IAM Identity Center and forbids long-term access keys. What should the developer do?
A. Create an IAM user and store its keys in appsettings.json.
B. Configure an SSO profile with the AWS CLI, sign in with aws sso login, and set the profile name in the SDK configuration.
C. Copy temporary credentials from the console into source code.
D. Use the root user's access keys.
Answer: B. The SDK's credential chain supports SSO profiles and refreshes from the cached token. A and D use long-term keys (D is never acceptable). C puts credentials in code and they expire.
Completion checklist
- The tool printed my account and role ARN
- Both unit tests pass without AWS access
- I can explain why
AWSSDK.SSOandAWSSDK.SSOOIDCare 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.
AWS clients and dependency injection
Register AWS SDK v4 clients in ASP.NET Core with AWSSDK.Extensions.NETCore.Setup: default options from configuration, per-client tuning, keyed clients for a second Region, correct lifetimes, per-environment settings, and tests that run without an AWS account.
ASP.NET Core Web API on AWS: the baseline
Prepare an ASP.NET Core API to run behind an Application Load Balancer: Kestrel settings, trusted forwarded headers, TLS terminated at the load balancer, health endpoints, graceful shutdown and the structure of Harbourline's reference Accounts API.