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.
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.SSOandAWSSDK.SSOOIDCmust be referenced even though no code uses them. - Register AWS clients in
Microsoft.Extensions.DependencyInjectionwithAddDefaultAWSOptionsandAddAWSService, and explain why clients should be long-lived. - Make your first STS and S3 calls, and diagnose
ExpiredToken,AccessDeniedand "unable to get credentials" errors.
Prerequisites
- AWS CLI v2 with SSO profiles โ you need a working
learn-sandboxprofile and a validaws 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:
- 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).
- A Region โ where the API endpoint lives, for example
us-east-1. - 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
| Part | What it is | Why it exists | Limits and sharp edges |
|---|---|---|---|
AWSSDK.Core | Signing (SigV4), retries, credential and Region resolution, HTTP pipeline | Shared plumbing for every service client | You 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 classes | Lets you take only what you use | Keep all AWSSDK.* packages on the same minor version line to avoid odd runtime errors |
AWSSDK.SSO, AWSSDK.SSOOIDC | Clients for the IAM Identity Center portal and token APIs | The SDK loads them at runtime when a profile uses sso_session | Not referenced by any using, so they look unused; remove them and SSO profiles fail at runtime |
AWSSDK.Extensions.NETCore.Setup | AddDefaultAWSOptions, AddAWSService and GetAWSOptions for DI and configuration | Makes AWS clients first-class citizens in ASP.NET Core and worker services | Configures 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.Bucketscan benullfor an account with no buckets, so writeresponse.Buckets ?? []. - Value-type properties are nullable.
S3Object.Sizeislong?andListObjectsV2Response.IsTruncatedisbool?. Compare with== trueor 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 equivalent | What's different |
|---|---|---|
Azure.Identity DefaultAzureCredential | SDK default credential chain | Both 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 token | aws sso login then the SDK reads the SSO token cache for an sso_session profile | The SDK reads the CLI's token cache directly; it does not shell out to the CLI |
| Managed identity on App Service / Functions | IAM role for Lambda, ECS task role, EC2 instance profile | Same 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 account | AmazonS3Client per Region (any bucket) | One S3 client can reach every bucket in its Region, and others through redirects |
RequestFailedException with Status and ErrorCode | AmazonServiceException with StatusCode and ErrorCode | AWS also has AmazonClientException for failures before the request reaches AWS |
Retry policy on ClientOptions.Retry | RetryMode and MaxErrorRetry on the client config | Standard 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-sandboxYou 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.15Versions 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.
| Option | Code | Use it when |
|---|---|---|
| Explicit profile | new CredentialProfileStoreChain().TryGetAWSCredentials("learn-sandbox", out var creds) | Tools and labs on a developer PC where you want no ambiguity |
AWSOptions.Profile with DI | services.AddDefaultAWSOptions(new AWSOptions { Profile = "learn-sandbox", Region = RegionEndpoint.USEast1 }) | ASP.NET Core or worker services, configured per environment |
| Default chain | new AmazonS3Client() with nothing passed | Code 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_PROFILERead 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 containsaws-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
<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>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 : 0The 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
Environment.GetEnvironmentVariable("AWS_PROFILE") ?? "learn-sandbox"โ honours the same variable the CLI uses, with the course default as fallback.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.services.AddDefaultAWSOptions(new AWSOptions { ... })โ stores default settings that every client registered afterwards will use.Profilenames a section in%USERPROFILE%\.aws\config;Regionsets the endpoint.services.AddAWSService<IAmazonSecurityTokenService>()โ registers the STS client interface as a singleton built from those defaults. Injecting the interface (IAmazonS3, notAmazonS3Client) is what lets you substitute a fake in unit tests.provider.GetRequiredService<IAmazonS3>()โ the client is created here, lazily. If the profile does not exist, this is where you get an exception.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.ListBucketsAsyncโ lists every general purpose bucket the account owns (in all Regions). It needss3:ListAllMyBuckets.buckets.Buckets ?? []โ the v4 null-collection rule. Forgetting it gives aNullReferenceExceptiononly in empty accounts, which is exactly the account you test with.AmazonServiceExceptionโ hasStatusCode(HTTP status),ErrorCode(for exampleAccessDenied) andRequestId. Log the request ID: AWS Support asks for it.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_IDis set, as the lab app does. - Do not let the app open a browser. For SSO credentials loaded with
CredentialProfileStoreChain, setSSOAWSCredentials.Options.SupportsGettingNewToken = false, so sign-in stays withaws 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 allows3:GetObjecton one prefix of one bucket, nothing more. - Log the request ID, never the credentials. Do not log
ImmutableCredentialsor 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.SSOOIDCas "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_PROFILEalways wins. โ it is the CLI habit โ environment-variable keys come first in the SDK chain. CheckGet-ChildItem Env:AWS_*. - Treating an empty response as an empty list. โ v3 habit โ v4 returns
nullcollections. Use?? []. - Catching
Exceptionand 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
| Symptom | Likely cause | Fix |
|---|---|---|
AmazonClientException mentioning the SSO token, or that the session expired | No valid aws sso login session | aws sso login --sso-session cea and run again |
Unable to get IAM security credentials from EC2 Instance Metadata Service | The chain found nothing and fell through to the last step | Set AWS_PROFILE or pass a profile; check the profile name |
No RegionEndpoint or ServiceURL configured | No Region from code, environment or profile | Set region = us-east-1 in the profile or pass RegionEndpoint.USEast1 |
Runtime error loading AWSSDK.SSO / AWSSDK.SSOOIDC | Packages missing | Add both package references |
AccessDenied on ListBuckets | Permission set lacks s3:ListAllMyBuckets or an SCP denies it | Check the permission set; STS should still work |
| Wrong account in the output | Environment-variable keys or AWS_PROFILE pointing elsewhere | Remove the variables; pass the profile explicitly |
InvalidClientTokenId | Old or fake access keys are being used | Delete them from environment and %USERPROFILE%\.aws\credentials |
ExpiredToken | Temporary role credentials expired mid-run | Sign in again; long jobs should run in AWS under a role |
NullReferenceException on .Buckets or .S3Objects | v4 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 logoutExercises
- ๐ข 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 usesnew AmazonSecurityTokenServiceClient()with no profile. Explain the error. Remove the variables afterwards. - ๐ก Challenge: Move the profile and Region into
appsettings.jsonunder an"AWS"section and load them withconfiguration.GetAWSOptions()(addMicrosoft.Extensions.Configuration.Json). Add anappsettings.Production.jsonwith 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
With both key variables set, step 2 of the chain (environment-variable BasicAWSCredentials) wins before any profile is considered. AWS rejects the example key with InvalidClientTokenId (an AmazonServiceException, because the request did reach AWS). The lesson: an environment variable you forgot about silently overrides AWS_PROFILE. Clean up with Remove-Item Env:AWS_ACCESS_KEY_ID, Env:AWS_SECRET_ACCESS_KEY.
Add "AWS": { "Profile": "learn-sandbox", "Region": "us-east-1" } to appsettings.json. Build configuration with new ConfigurationBuilder().AddJsonFile("appsettings.json").AddJsonFile($"appsettings.{env}.json", optional: true).Build(), then services.AddDefaultAWSOptions(configuration.GetAWSOptions()). In appsettings.Production.json set only "Region". Because later files override earlier ones key by key, you also need to clear the profile: set "Profile": "" or keep the profile only in appsettings.Development.json. The second approach is cleaner: production configuration then never mentions a profile.
Get-ChildItem Env:AWS_*for the service account and machine-wide ([Environment]::GetEnvironmentVariables('Machine')): stray keys win first. 2.AWS_PROFILEset at machine level. 3. A[default]profile in the service account's.aws\credentialsor.aws\config(step 6). 4. Whether the agent runs on EC2 with an instance profile (step 8). 5. Runaws sts get-caller-identityas the service account to see the ARN, then trace that account in Organizations. Fix: remove the stray source and make the app pass credentials explicitly or run under a dedicated role. Raise it as a security finding, because an unknown account's credentials on a build agent is an incident until proven otherwise.
Knowledge check
Answer: The environment-variable keys. They are steps 1โ2 of the default chain; AWS_PROFILE is step 5. Only credentials passed explicitly to the client come before them.
Answer: Resolving an sso_session profile requires calls to the Identity Center OIDC and portal APIs. The core SDK loads those service clients dynamically at runtime, so the compiler never sees a dependency. Without them, the profile fails to load at runtime.
Answer: AmazonServiceException means AWS received the request and returned an error (it has an HTTP status, error code and request ID). AmazonClientException means the SDK could not complete the request itself, for example no credentials, an expired SSO token or no Region.
Answer: Clients are thread-safe and hold HTTP connection pools and cached credentials. Creating one per request wastes sockets, adds latency and repeats credential resolution.
Answer: The response contained no objects. v4 returns null instead of an empty list by default, so code must handle null (for example ?? []).
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.GetCallerIdentityshows 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
A .NET application on a self-hosted CI agent (not on AWS) must read from an S3 bucket. The security team forbids long-lived access keys. What is the most appropriate approach?
A. Create an IAM user, store its access key in the agent's environment variables, and rotate it monthly
B. Configure the agent to obtain temporary credentials through an OIDC federation trust with an IAM role, and let the SDK pick them up from the web-identity environment variables
C. Embed the access key in appsettings.json encrypted with DPAPI
D. Use the root user's credentials stored in AWS Secrets Manager
Answer: B. Web-identity federation gives short-lived role credentials and the SDK's chain reads AWS_WEB_IDENTITY_TOKEN_FILE and AWS_ROLE_ARN. A and C are long-lived keys, regardless of rotation or encryption. D uses the root user and still needs credentials to reach Secrets Manager.
A developer sets AWS_PROFILE=test but the application writes to the production account. aws configure list shows the access key comes from env. What is the cause?
A. The test profile has the production Region
B. AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set and take precedence over AWS_PROFILE
C. The SDK always uses the [default] profile
D. IAM Identity Center sessions are account-wide
Answer: B. Environment-variable keys come before named profiles in the chain. A changes the endpoint, not the account. C is false; [default] is only used when nothing earlier matches. D is meaningless: a permission set maps to specific accounts.
Which statement about the AWS SDKs is correct?
A. They bypass IAM because they run inside your application B. They call the same AWS APIs as the Management Console and the CLI, and every call is authorised by IAM C. They only work from inside AWS D. They require long-lived access keys
Answer: B. All three interfaces call the same signed APIs. A is false: IAM evaluates every request. C and D are false: the SDK works anywhere with network access and supports temporary credentials.
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 logoutat 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.SSOandAWSSDK.SSOOIDCare referenced. - Register clients once with
AddDefaultAWSOptionsandAddAWSService, inject interfaces, and fake them in tests. - v4 returns
nullcollections and nullable value types: code defensively. AmazonServiceExceptionmeans AWS said no;AmazonClientExceptionmeans 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.
AWS CLI v2 with SSO profiles
Configure the AWS CLI v2 to sign in through IAM Identity Center, use named profiles safely, shape output with --query, page through results and prove that no long-lived access keys exist on your PC.
Free Tier and billing
Understand the 2025 Free plan and Paid plan, what is always free, how AWS bills you, where to see credits and costs, how cost allocation tags work, and the traps that turn a free lab into a bill.