Skip to Content
Cloud Engineering Academy
1. Cloud Computing & AWS Fundamentals

AWS SDK for .NET: first contact

Call AWS from C# with the AWS SDK for .NET v4: how the SDK finds credentials and a Region, how SSO profiles work from code, how to register clients with dependency injection, and how to read the errors you will meet on day one.

beginnerโฑ 1 h 15 min๐ŸŸข FreeCLF-C02DVA-C03

Assumes: .NET 10 LTS ยท AWS SDK for .NET v4 (AWSSDK.Core 4.1.x) ยท AWSSDK.Extensions.NETCore.Setup 4.1 ยท AWS CLI v2 ยท Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Explain what the AWS SDK for .NET is, how its NuGet packages are split, and what changed in version 4 that affects everyday code.
  • Recite the credential search order the SDK uses when you do not pass credentials, and predict which credentials win when several exist.
  • Recite the Region resolution order, and explain the "no RegionEndpoint or ServiceURL configured" error.
  • Use an IAM Identity Center (SSO) profile from C# without any access keys, and explain why AWSSDK.SSO and AWSSDK.SSOOIDC must be referenced even though no code uses them.
  • Register AWS clients in Microsoft.Extensions.DependencyInjection with AddDefaultAWSOptions and AddAWSService, and explain why clients should be long-lived.
  • Make your first STS and S3 calls, and diagnose ExpiredToken, AccessDenied and "unable to get credentials" errors.

Prerequisites

  • AWS CLI v2 with SSO profiles โ€” you need a working learn-sandbox profile and a valid aws sso login
  • IAM fundamentals โ€” roles, policies and temporary credentials
  • The Module 0 lab Verify your setup with C# is a good warm-up; this lesson explains why that code works
  • Tools: .NET 10 SDK (or Docker), Visual Studio 2026 or VS Code, AWS CLI v2

Why this matters in banking

A Harbourline Bank developer ships a reconciliation job that runs nightly on a build agent. On their PC it worked perfectly. On the agent it reads statements from the production account instead of the test account, because someone had left AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the agent's machine-wide environment variables two years earlier. The SDK did exactly what it is documented to do: environment-variable keys come before profiles. Nobody on the team knew that order.

Credential and Region resolution is invisible when it works and baffling when it does not. In a bank it is also a control: auditors ask "how does this application authenticate to the cloud, and how do you know it cannot use a developer's personal access?" You should be able to answer with the exact order the SDK follows, and show code that makes the choice explicit.

The idea in plain language

The AWS SDK for .NET is a set of NuGet packages that wrap AWS's HTTPS APIs in C# classes. Instead of hand-crafting a signed HTTP request to https://sts.us-east-1.amazonaws.com/, you write:

var response = await sts.GetCallerIdentityAsync(new GetCallerIdentityRequest());

Every call needs three things:

  1. Credentials โ€” who you are. On your PC these should be temporary credentials obtained from IAM Identity Center. In AWS they come from an IAM role attached to the compute (Lambda, ECS task, EC2 instance).
  2. A Region โ€” where the API endpoint lives, for example us-east-1.
  3. Permissions โ€” the IAM policies that allow the action. The SDK cannot help with this; AWS evaluates it on every call.

If you do not give the client credentials or a Region, the SDK searches for them in a fixed order. That search is the single most important thing to understand in this lesson.

Analogy: The SDK is a courier who needs an ID badge (credentials) and a delivery address (Region). If you hand over a badge, the courier uses it. If you do not, the courier checks your coat pocket (environment variables), then the drawer in reception (profiles in .aws\config), then asks building security (container or instance role). The first badge found is the one used, even if it belongs to someone else.

What problem the AWS service solves

PartWhat it isWhy it existsLimits and sharp edges
AWSSDK.CoreSigning (SigV4), retries, credential and Region resolution, HTTP pipelineShared plumbing for every service clientYou rarely reference it directly; it comes with every service package
AWSSDK.<Service> (e.g. AWSSDK.S3, AWSSDK.SecurityToken)One package per service, with a client class such as AmazonS3Client and request/response classesLets you take only what you useKeep all AWSSDK.* packages on the same minor version line to avoid odd runtime errors
AWSSDK.SSO, AWSSDK.SSOOIDCClients for the IAM Identity Center portal and token APIsThe SDK loads them at runtime when a profile uses sso_sessionNot referenced by any using, so they look unused; remove them and SSO profiles fail at runtime
AWSSDK.Extensions.NETCore.SetupAddDefaultAWSOptions, AddAWSService and GetAWSOptions for DI and configurationMakes AWS clients first-class citizens in ASP.NET Core and worker servicesConfigures the client once; credentials still follow the normal resolution rules

What changed in v4 (the version this course uses). The ones you will notice in day-to-day code:

  • Collections are null, not empty, when a response contains no items. response.Buckets can be null for an account with no buckets, so write response.Buckets ?? [].
  • Value-type properties are nullable. S3Object.Size is long? and ListObjectsV2Response.IsTruncated is bool?. Compare with == true or use ?? 0.
  • Supported targets are modern .NET and .NET Framework 4.7.2 or later. Old .NET Framework versions and the v3-era "portable" targets are gone.
  • Several long-deprecated types and methods were removed. If you copy a v3 sample from an old blog post and it does not compile, check the migration guide.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Azure.Identity DefaultAzureCredentialSDK default credential chainBoth try a list of sources in order. The AWS chain checks environment-variable keys before profiles, which surprises people
az login then DefaultAzureCredential uses the Azure CLI tokenaws sso login then the SDK reads the SSO token cache for an sso_session profileThe SDK reads the CLI's token cache directly; it does not shell out to the CLI
Managed identity on App Service / FunctionsIAM role for Lambda, ECS task role, EC2 instance profileSame idea: no secrets in config, credentials rotate automatically
services.AddAzureClients(b => b.AddBlobServiceClient(...))services.AddDefaultAWSOptions(...) + services.AddAWSService<IAmazonS3>()AWS clients take a Region instead of an account URL
BlobServiceClient per storage accountAmazonS3Client per Region (any bucket)One S3 client can reach every bucket in its Region, and others through redirects
RequestFailedException with Status and ErrorCodeAmazonServiceException with StatusCode and ErrorCodeAWS also has AmazonClientException for failures before the request reaches AWS
Retry policy on ClientOptions.RetryRetryMode and MaxErrorRetry on the client configStandard retry mode with exponential backoff is the default

Architecture

How a single SDK call is resolved and sent:

The search stops at the first source that produces credentials. Steps 1โ€“3 sit above the profile steps, so stray environment variables override AWS_PROFILE.

Security-boundary view. On your PC, the only long-lived secret is your Identity Center password plus MFA, typed into a browser. The CLI stores a short-lived token in %USERPROFILE%\.aws\sso\cache. The SDK swaps that token for role credentials that last for the permission set's session duration (one hour by default). Nothing in your code or configuration files is a secret.

Step-by-step implementation

Check your sign-in from the CLI first

If the CLI cannot call AWS, the SDK will not either, so rule that out first.

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

You should see an ARN containing assumed-role/AWSReservedSSO_SandboxAdmin_....

Create a console project and add packages

dotnet new console -n Harbourline.SdkFirstContact -f net10.0
cd Harbourline.SdkFirstContact
dotnet add package AWSSDK.SecurityToken --version 4.1.0.2
dotnet add package AWSSDK.S3 --version 4.1.1
dotnet add package AWSSDK.SSO --version 4.1.0.2
dotnet add package AWSSDK.SSOOIDC --version 4.1.0.2
dotnet add package AWSSDK.Extensions.NETCore.Setup --version 4.1.0.2
dotnet add package Microsoft.Extensions.DependencyInjection --version 10.0.15

Versions were checked on nuget.org on 2026-11-17. Newer 4.x patch versions are fine; keep them aligned.

Decide how the app gets credentials

You have three options. Pick deliberately.

OptionCodeUse it when
Explicit profilenew CredentialProfileStoreChain().TryGetAWSCredentials("learn-sandbox", out var creds)Tools and labs on a developer PC where you want no ambiguity
AWSOptions.Profile with DIservices.AddDefaultAWSOptions(new AWSOptions { Profile = "learn-sandbox", Region = RegionEndpoint.USEast1 })ASP.NET Core or worker services, configured per environment
Default chainnew AmazonS3Client() with nothing passedCode that will run in AWS (Lambda, ECS), where the role is the only source

The production rule is simple: in AWS, use the default chain and let the compute role supply credentials. Do not ship a profile name into a Lambda function.

Write the program

Use the complete code below. It registers clients with DI, calls STS and S3, and prints which identity was used.

Run it, then break it on purpose

dotnet run
# Now simulate an expired session:
aws sso logout
dotnet run
# And a wrong profile:
$env:AWS_PROFILE = "does-not-exist"; dotnet run; Remove-Item Env:AWS_PROFILE

Read each error and match it against the troubleshooting table. Then sign in again.

AWS Console instructions

The SDK has no console of its own, but two console pages help you check what the SDK did:

  • Console โ†’ IAM Identity Center โ†’ Permission sets โ†’ SandboxAdmin โ†’ Session duration shows how long the role credentials the SDK receives will last.
  • Console โ†’ CloudTrail โ†’ Event history, filter Event name = ListBuckets, shows your SDK call with the user agent string (it contains aws-sdk-dotnet) and the role session name, which is your Identity Center user name. Events can take a few minutes to appear.

AWS CLI

The CLI and the SDK share the same configuration files, so the CLI is the fastest way to debug what the SDK will see.

# Which profiles exist? (the SDK reads the same %USERPROFILE%\.aws\config)
aws configure list-profiles

# Where does each value come from for this profile? TYPE shows sso, env, shared-credentials-file...
aws configure list --profile learn-sandbox

# Who would I be? The SDK's GetCallerIdentity returns the same ARN.
aws sts get-caller-identity --profile learn-sandbox

# Are stray key variables set? These would beat AWS_PROFILE in the SDK.
Get-ChildItem Env:AWS_*

# Is there a credentials file with keys in it? It should not exist, or contain no keys.
Test-Path "$env:USERPROFILE\.aws\credentials"

Infrastructure as Code

Not applicable to this lesson: nothing is deployed. The module exercise includes Terraform for a small CloudFront status page.

Complete code

Harbourline.SdkFirstContact.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AWSSDK.S3" Version="4.1.1" />
    <PackageReference Include="AWSSDK.SecurityToken" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="4.1.0.2" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.15" />
    <!-- Loaded at runtime to resolve sso_session profiles. Do not remove. -->
    <PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
  </ItemGroup>
</Project>
Program.cs
using Amazon;
using Amazon.Extensions.NETCore.Setup;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using Microsoft.Extensions.DependencyInjection;

// 1. Decide profile and Region explicitly. On a PC: a named SSO profile. In AWS: leave Profile null.
var profile = Environment.GetEnvironmentVariable("AWS_PROFILE") ?? "learn-sandbox";
var runningInAws = Environment.GetEnvironmentVariable("AWS_EXECUTION_ENV") is not null;

var services = new ServiceCollection();
services.AddDefaultAWSOptions(new AWSOptions
{
    Profile = runningInAws ? null : profile,
    Region = RegionEndpoint.USEast1,
});

// 2. Register clients. Each is created once (singleton) and reused: clients are thread-safe
//    and hold connection pools, so creating one per request wastes sockets and time.
services.AddAWSService<IAmazonSecurityTokenService>();
services.AddAWSService<IAmazonS3>();

await using var provider = services.BuildServiceProvider();
var sts = provider.GetRequiredService<IAmazonSecurityTokenService>();
var s3 = provider.GetRequiredService<IAmazonS3>();

try
{
    // 3. Who am I? Needs no IAM permission, so it is the perfect first call.
    var me = await sts.GetCallerIdentityAsync(new GetCallerIdentityRequest());
    Console.WriteLine($"Account : {me.Account}");
    Console.WriteLine($"ARN     : {me.Arn}");

    // 4. A call that IS permission-checked: s3:ListAllMyBuckets.
    var buckets = await s3.ListBucketsAsync(new ListBucketsRequest());
    var names = (buckets.Buckets ?? []).Select(b => b.BucketName).ToList(); // v4: null when empty
    Console.WriteLine($"Buckets : {names.Count}");
    foreach (var name in names.Take(10))
    {
        Console.WriteLine($"  - {name}");
    }

    return 0;
}
catch (AmazonServiceException ex)
{
    // AWS received the request and refused it.
    Console.Error.WriteLine($"AWS said no: {ex.StatusCode} {ex.ErrorCode} - {ex.Message}");
    return 1;
}
catch (AmazonClientException ex)
{
    // The SDK could not build or send a signed request (no credentials, expired SSO token, no Region).
    Console.Error.WriteLine($"SDK could not call AWS: {ex.Message}");
    Console.Error.WriteLine("Try: aws sso login --sso-session cea");
    return 1;
}

Expected output (IDs are fictional):

Account : 111122223333
ARN     : arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_SandboxAdmin_0a1b2c3d4e5f6a7b/alex.learner
Buckets : 0

The module exercise builds on this with a full lab app in labs/m01-hello-aws/, which loads the profile explicitly, creates a locked-down bucket and has 70+ unit tests that run without AWS.

Code explained line by line

  1. Environment.GetEnvironmentVariable("AWS_PROFILE") ?? "learn-sandbox" โ€” honours the same variable the CLI uses, with the course default as fallback.
  2. AWS_EXECUTION_ENV โ€” Lambda and ECS set this variable. When it exists, the code passes no profile, so the SDK falls through to the container or Lambda role. โš  VERIFY that your compute platform sets it before relying on this in production; an explicit configuration flag per environment is more robust.
  3. services.AddDefaultAWSOptions(new AWSOptions { ... }) โ€” stores default settings that every client registered afterwards will use. Profile names a section in %USERPROFILE%\.aws\config; Region sets the endpoint.
  4. services.AddAWSService<IAmazonSecurityTokenService>() โ€” registers the STS client interface as a singleton built from those defaults. Injecting the interface (IAmazonS3, not AmazonS3Client) is what lets you substitute a fake in unit tests.
  5. provider.GetRequiredService<IAmazonS3>() โ€” the client is created here, lazily. If the profile does not exist, this is where you get an exception.
  6. GetCallerIdentityAsync(new GetCallerIdentityRequest()) โ€” STS returns the account, the caller ARN and a user ID. No policy can deny it, which makes it a reliable "am I signed in?" check.
  7. ListBucketsAsync โ€” lists every general purpose bucket the account owns (in all Regions). It needs s3:ListAllMyBuckets.
  8. buckets.Buckets ?? [] โ€” the v4 null-collection rule. Forgetting it gives a NullReferenceException only in empty accounts, which is exactly the account you test with.
  9. AmazonServiceException โ€” has StatusCode (HTTP status), ErrorCode (for example AccessDenied) and RequestId. Log the request ID: AWS Support asks for it.
  10. AmazonClientException โ€” thrown before anything reaches AWS. The most common message on a developer PC is about an expired or missing SSO token.

Security considerations

  • No keys in code, config or environment. The code above contains no secret. Its only inputs are a profile name and a Region.
  • Know the chain order. Environment-variable keys (steps 1โ€“2) beat every profile. On shared build agents, check machine-wide variables. Your app can warn when AWS_ACCESS_KEY_ID is set, as the lab app does.
  • Do not let the app open a browser. For SSO credentials loaded with CredentialProfileStoreChain, set SSOAWSCredentials.Options.SupportsGettingNewToken = false, so sign-in stays with aws sso login. Background services must never prompt.
  • In AWS, roles only. Lambda, ECS and EC2 provide role credentials through the chain's later steps. A profile name in production configuration is a smell.
  • Least privilege. The lab permission set is broad (SandboxAdmin). A real reconciliation job's role would allow s3:GetObject on one prefix of one bucket, nothing more.
  • Log the request ID, never the credentials. Do not log ImmutableCredentials or the contents of the SSO cache.

โš  Learning shortcut โ€” not for production

This lesson uses the broad SandboxAdmin permission set and a hard-coded Region. In production, the application runs under a dedicated IAM role with only the actions it needs, the Region comes from environment configuration, and the code never chooses a profile: the platform supplies credentials.

Banking use case

Harbourline Bank's statement service runs as an ECS Fargate task in the payments-prod account. Its task role allows s3:GetObject and s3:PutObject on arn:aws:s3:::hl-statements-prod/statements/* and nothing else. The code is the same as on a developer PC except that AWSOptions.Profile is null, so the SDK reaches step 7 (container credentials) and uses the task role.

During a security review, the architect shows three things: the task definition has no environment variables starting with AWS_ACCESS; the CI pipeline fails the build if a credentials file is found in the image; and CloudTrail shows every S3 call made by the role session. That is a credible answer to "how does this service authenticate, and how do you know?". The bank's risk team still decides whether the controls are sufficient; the code alone does not make the service compliant with anything.

Common mistakes

  • Removing AWSSDK.SSO / AWSSDK.SSOOIDC as "unused". โ†’ IDE clean-up tools flag them โ†’ the app compiles and then fails when the profile loads. Keep them, with a comment.
  • Creating a new client per request. โ†’ it looks harmless โ†’ you exhaust sockets and re-resolve credentials each time. Register clients as singletons.
  • Assuming AWS_PROFILE always wins. โ†’ it is the CLI habit โ†’ environment-variable keys come first in the SDK chain. Check Get-ChildItem Env:AWS_*.
  • Treating an empty response as an empty list. โ†’ v3 habit โ†’ v4 returns null collections. Use ?? [].
  • Catching Exception and printing "AWS error". โ†’ you lose the distinction between "AWS refused" (AmazonServiceException) and "never reached AWS" (AmazonClientException), which point to completely different fixes.
  • Using the Region of your bucket for STS by habit. โ†’ harmless here, but some global services have one control-plane Region. Read each service's endpoint documentation.

Troubleshooting

SymptomLikely causeFix
AmazonClientException mentioning the SSO token, or that the session expiredNo valid aws sso login sessionaws sso login --sso-session cea and run again
Unable to get IAM security credentials from EC2 Instance Metadata ServiceThe chain found nothing and fell through to the last stepSet AWS_PROFILE or pass a profile; check the profile name
No RegionEndpoint or ServiceURL configuredNo Region from code, environment or profileSet region = us-east-1 in the profile or pass RegionEndpoint.USEast1
Runtime error loading AWSSDK.SSO / AWSSDK.SSOOIDCPackages missingAdd both package references
AccessDenied on ListBucketsPermission set lacks s3:ListAllMyBuckets or an SCP denies itCheck the permission set; STS should still work
Wrong account in the outputEnvironment-variable keys or AWS_PROFILE pointing elsewhereRemove the variables; pass the profile explicitly
InvalidClientTokenIdOld or fake access keys are being usedDelete them from environment and %USERPROFILE%\.aws\credentials
ExpiredTokenTemporary role credentials expired mid-runSign in again; long jobs should run in AWS under a role
NullReferenceException on .Buckets or .S3Objectsv4 null collections?? []

Cost and cleanup

Cost: $0. STS GetCallerIdentity has no charge, and a handful of S3 ListBuckets requests cost a tiny fraction of a cent (S3 bills requests per thousand). Nothing is created, so nothing needs deleting. At the end of the session:

aws sso logout

Exercises

  • ๐ŸŸข Guided: Run the program. Then set $env:AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE" and $env:AWS_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" (AWS's documented example values), and run a version of the program that uses new AmazonSecurityTokenServiceClient() with no profile. Explain the error. Remove the variables afterwards.
  • ๐ŸŸก Challenge: Move the profile and Region into appsettings.json under an "AWS" section and load them with configuration.GetAWSOptions() (add Microsoft.Extensions.Configuration.Json). Add an appsettings.Production.json with no profile.
  • ๐Ÿ”ด Live problem: A colleague's worker service runs fine on their laptop but on the shared Windows build agent it lists buckets from an account nobody recognises. You have read-only access to the agent. Write down, in order, what you check and why.

Assignment

Add a docs/credentials.md to your portfolio repository that explains, for the module exercise app, exactly where credentials and the Region come from on a developer PC and in AWS, with the chain order and the controls you rely on. Write it for an auditor, not a developer.

Solutions

Knowledge check

Interview questions

  • "How does your .NET service authenticate to AWS?" โ€” In AWS through the compute role (Lambda execution role, ECS task role) found by the SDK's default chain; locally through IAM Identity Center SSO profiles with short-lived credentials. No long-lived keys anywhere, and CI checks for them.
  • "A service suddenly talks to the wrong account. What do you check?" โ€” The credential chain in order: explicit credentials in code, environment-variable keys, web-identity variables, AWS_PROFILE, the default profile, then container and instance roles. GetCallerIdentity shows which identity won.
  • "How do you unit-test code that calls S3?" โ€” Depend on IAmazonS3, inject it via DI, and use a fake or mocking library in tests. Keep pure logic (naming, validation, policies) separate from the calls.
  • "What changed in SDK v4 that bit you?" โ€” Null collections and nullable value types in responses; removed legacy types. Mention reading the migration guide before upgrading.

Certification practice

Completion checklist

  • I can list the eight steps of the SDK credential chain in order
  • I can explain the Region resolution order and the "no RegionEndpoint" error
  • My console app prints my Identity Center role ARN
  • I broke it three ways (logout, wrong profile, stray keys) and fixed each
  • I ran aws sso logout at the end of the session

Key takeaways

  • The SDK tries credentials in a fixed order: explicit, environment keys, web identity, named profile, AWS_PROFILE, [default], container, instance metadata. First match wins.
  • SSO profiles work from code with no keys, provided AWSSDK.SSO and AWSSDK.SSOOIDC are referenced.
  • Register clients once with AddDefaultAWSOptions and AddAWSService, inject interfaces, and fake them in tests.
  • v4 returns null collections and nullable value types: code defensively.
  • AmazonServiceException means AWS said no; AmazonClientException means the call never got there.

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