Skip to Content
Cloud Engineering Academy
0. Orientation & a Safe Learning Environment

Lab: verify your setup with C#

Run a .NET 10 console app that uses your IAM Identity Center profile to call STS and S3, and prints the account, caller ARN and Region.

beginnerโฑ 45 min๐ŸŸข FreeCLF-C02DVA-C03

Assumes: .NET 10 LTS ยท AWS SDK for .NET v4 (AWSSDK.SecurityToken 4.1.0.2, AWSSDK.S3 4.1.1, AWSSDK.SSO 4.1.0.1, AWSSDK.SSOOIDC 4.1.0.2) ยท AWS CLI v2 ยท xUnit v3 4.0.3 ยท Region us-east-1. Verified against official sources on 2026-11-17.

Learning objectives

By the end of this lab you can:

  • Run a C# console app that authenticates with an IAM Identity Center (SSO) profile โ€” no access keys anywhere.
  • Explain which NuGet packages the AWS SDK for .NET v4 needs to resolve SSO profiles, and why two of them are needed only at runtime.
  • Read the output of STS GetCallerIdentity (account, ARN, principal type) and tell an Identity Center session from a root or IAM user session.
  • Diagnose the three most common first-day failures: expired SSO token, wrong profile, AccessDenied.
  • Run the lab's xUnit v3 tests on Microsoft.Testing.Platform.

Prerequisites

  • Secure your AWS account โ€” a sandbox account and the SandboxAdmin permission set (Path A), or an IAM user with MFA and SignInLocalDevelopmentAccess (Path B).
  • Tooling setup on Windows โ€” .NET 10 SDK, AWS CLI v2 and a learn-sandbox profile.
  • Cost guardrails โ€” active, even though this lab is free.
  • Lab code: labs/00-verify-setup/ in the course repository.

Why this matters in banking

On your first day in a bank's AWS team, the first ticket is often "I can't connect". Being able to prove, in one command, which identity, which account and which Region your code is using saves hours โ€” and it is the first thing a security reviewer asks when code touches production data. GetCallerIdentity is the AWS equivalent of checking your badge before you enter the vault: it costs nothing, needs no permissions and tells you exactly who AWS thinks you are.

The idea in plain language

Your .NET code never sees a password or a permanent key. Instead:

  1. You sign in once with aws sso login (browser + MFA). The CLI caches a token on disk.
  2. Your app asks the SDK for the credentials of profile learn-sandbox.
  3. The SDK reads the profile from %USERPROFILE%\.aws\config, finds the cached token, and exchanges it for temporary role credentials for the SandboxAdmin permission set.
  4. The SDK signs the STS and S3 requests with those credentials.

Analogy: Signing in is collecting your day badge at reception. The profile is the note saying which floor and which room you are going to. The SDK is the lift that reads your badge and takes you only to that floor. GetCallerIdentity is looking at your own badge in the mirror.

What problem the AWS services solve

Service / callWhat it doesNotes
AWS STS GetCallerIdentityReturns the account ID, user ID and ARN of the callerRequires no IAM permission and cannot be denied by a policy, so it isolates "can I authenticate?" from "am I allowed?"
Amazon S3 ListBucketsLists the buckets in the accountNeeds s3:ListAllMyBuckets; a good first authorised call. Global, so it works from any Region allowed by the SCP
IAM Identity Center (via the SSO and SSO OIDC APIs)Turns your cached token into role credentialsUsed by the SDK behind the scenes; that is why AWSSDK.SSO and AWSSDK.SSOOIDC must be referenced

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
az account showaws sts get-caller-identityReturns the ARN of the role session, not your user object
DefaultAzureCredential / AzureCliCredentialSDK credential resolution from a named profile (CredentialProfileStoreChain)You choose the profile explicitly; SSO needs extra runtime packages
Microsoft Graph /meSTS GetCallerIdentitySTS needs no permissions
BlobServiceClient.GetBlobContainersAsyncAmazonS3Client.ListBucketsAsyncIn SDK v4, empty collections come back as null

Architecture

Security-boundary view: the only secret on your PC is the short-lived token and role credentials in %USERPROFILE%\.aws\sso\cache, created by the CLI. The app never reads or prints them; it only passes the profile name to the SDK.

Step-by-step implementation

Get the code and look at the project file

Open labs/00-verify-setup/ from the course repository in your IDE. The key part of src/VerifySetup/VerifySetup.csproj:

src/VerifySetup/VerifySetup.csproj
<ItemGroup>
  <!-- AWS SDK for .NET v4. Versions checked on nuget.org on 2026-11-17. -->
  <PackageReference Include="AWSSDK.SecurityToken" Version="4.1.0.2" />
  <PackageReference Include="AWSSDK.S3" Version="4.1.1" />
  <!-- Required at RUNTIME so IAM Identity Center (SSO) profiles resolve.
       Leaving them out compiles fine but fails when the profile is loaded. -->
  <PackageReference Include="AWSSDK.SSO" Version="4.1.0.1" />
  <PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
  <!-- Only needed for the Free-plan path, where you sign in with `aws login` (login_session profiles). -->
  <PackageReference Include="AWSSDK.Signin" Version="4.1.0.1" />
</ItemGroup>

Sign in

aws sso login --sso-session cea
# Path B (Free plan, single account):
# aws login --profile learn-sandbox

Run the app

cd labs/00-verify-setup
dotnet run --project src/VerifySetup -- --profile learn-sandbox

Everything after -- goes to the app, not to dotnet run.

Compare with the expected output

AWS setup check - Cloud Engineering Academy, lab 00
----------------------------------------------------
Profile    : learn-sandbox (from command line)
Region     : us-east-1 (from the profile in your AWS config file)
Account    : 111122223333
Caller ARN : arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_SandboxAdmin_0a1b2c3d4e5f6a7b/alex.learner
Principal  : IAM Identity Center permission set 'SandboxAdmin' (session: alex.learner)
S3         : 0 bucket(s) visible (first page of results)
Checks     :
  [OK]   Signed in through IAM Identity Center (short-lived credentials).
  [OK]   Region is us-east-1, the course default.
Result     : PASS

Your account ID, role suffix and session name will differ. On Path B the principal line reads IAM user '<name>' with a [WARN] reminding you never to create access keys for it; the result is still PASS.

Validate the result independently

  1. Open the AWS access portal: the account ID next to cea-sandbox must match the Account line.
  2. Run aws sts get-caller-identity --profile learn-sandbox โ€” the Arn must match Caller ARN.
  3. Run with --mask-account and confirm only the last four digits are shown.

Run the tests

dotnet test --solution VerifySetup.slnx

Expect 31 tests passed. They test argument parsing, profile/Region precedence, ARN parsing, report formatting and error advice โ€” none of them calls AWS, so they run offline and in CI.

Break it on purpose (troubleshooting practice)

# 1. Expired / missing SSO token
aws sso logout
dotnet run --project src/VerifySetup -- --profile learn-sandbox

# 2. Wrong profile name
aws sso login --sso-session cea
dotnet run --project src/VerifySetup -- --profile learn-sandbx

# 3. Stray environment keys (fake values โ€” never use real ones)
$env:AWS_ACCESS_KEY_ID = "AKIAEXAMPLEEXAMPLE00"; $env:AWS_SECRET_ACCESS_KEY = "fake"
dotnet run --project src/VerifySetup -- --profile learn-sandbox
Remove-Item Env:AWS_ACCESS_KEY_ID, Env:AWS_SECRET_ACCESS_KEY

Compare what you see with the troubleshooting table. In case 3 the app still uses your profile (it loads credentials explicitly from it) but prints a [WARN] because the AWS CLI and any code using the default credential chain would pick up those keys instead.

AWS Console instructions

Only for validation: AWS access portal โ†’ cea-sandbox โ†’ account ID and, optionally, S3 โ†’ Buckets in the sandbox to compare the bucket count. Nothing is created in the console.

AWS CLI

# The CLI equivalent of the app's two calls.
aws sts get-caller-identity --profile learn-sandbox
aws s3api list-buckets --query "length(Buckets)" --profile learn-sandbox

# Where is each setting coming from?
aws configure list --profile learn-sandbox

Infrastructure as Code

Not applicable โ€” the lab creates no AWS resources.

Complete code

The full project (with tests) is in labs/00-verify-setup/. This is Program.cs, the only file that calls AWS:

src/VerifySetup/Program.cs
// Lab 00 - verify your AWS setup.
// Uses a named profile (IAM Identity Center / SSO by default) to call:
//   1. STS GetCallerIdentity  - "who am I?"  (needs no IAM permission)
//   2. S3 ListBuckets         - "can I make a normal, permission-checked call?"
// and prints the account, caller ARN and Region. It never creates, changes or deletes anything.

using Amazon;
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using Cea.Labs.VerifySetup;

CommandLineOptions options;
try
{
    options = RunSettings.ParseArguments(args);
}
catch (ArgumentException ex)
{
    Console.Error.WriteLine(ex.Message);
    return 2;
}

if (options.ShowHelp)
{
    Console.WriteLine(RunSettings.HelpText);
    return 0;
}

Func<string, string?> getEnv = Environment.GetEnvironmentVariable;
var profileSetting = RunSettings.ResolveProfile(options.Profile, getEnv);

// Read the profile from %USERPROFILE%\.aws\config (and the credentials file, if one exists).
var chain = new CredentialProfileStoreChain();
if (!chain.TryGetProfile(profileSetting.Value, out var profile))
{
    Console.Error.WriteLine(ErrorAdvisor.ProfileNotFound(profileSetting.Value));
    return 2;
}

if (!chain.TryGetAWSCredentials(profileSetting.Value, out var credentials))
{
    Console.Error.WriteLine($"Profile '{profileSetting.Value}' exists but no credentials could be built from it. Check its settings.");
    return 2;
}

// For SSO profiles, never pop up a browser from this app: sign-in is the CLI's job (aws sso login).
if (credentials is SSOAWSCredentials sso)
{
    sso.Options.ClientName = "cea-lab-00-verify-setup"; // must not contain spaces
    sso.Options.SupportsGettingNewToken = false;
}

var regionSetting = RunSettings.ResolveRegion(options.Region, getEnv, profile.Region?.SystemName);
var region = RegionEndpoint.GetBySystemName(regionSetting.Value);

try
{
    // 1. Who am I? GetCallerIdentity works even when every other permission is denied.
    using var sts = new AmazonSecurityTokenServiceClient(credentials, region);
    var identity = await sts.GetCallerIdentityAsync(new GetCallerIdentityRequest());
    var caller = CallerIdentity.Parse(identity.Arn);

    // 2. A normal call that IS checked against your permissions (s3:ListAllMyBuckets).
    int? bucketCount = null;
    if (!options.SkipS3)
    {
        using var s3 = new AmazonS3Client(credentials, region);
        var buckets = await s3.ListBucketsAsync(new ListBucketsRequest());
        // SDK v4: collections are null (not empty) when the response has no items.
        bucketCount = buckets.Buckets?.Count ?? 0;
    }

    var report = new SetupReport(
        profileSetting,
        regionSetting,
        caller,
        bucketCount,
        options.MaskAccount,
        RunSettings.HasStaticKeysInEnvironment(getEnv));

    Console.WriteLine(report.Format());
    return report.Passed ? 0 : 1;
}
catch (AmazonServiceException ex)
{
    // The request reached AWS and AWS said no (e.g. AccessDenied, ExpiredToken).
    Console.Error.WriteLine($"AWS returned an error: {ex.ErrorCode} - {ex.Message}");
    Console.Error.WriteLine(ErrorAdvisor.Advise(ex.ErrorCode, ex.GetType().Name, ex.Message, profileSetting.Value));
    return 1;
}
catch (AmazonClientException ex)
{
    // The SDK could not even build a signed request (e.g. no valid SSO token).
    Console.Error.WriteLine($"The AWS SDK could not make the request: {ex.Message}");
    Console.Error.WriteLine(ErrorAdvisor.Advise(null, ex.GetType().Name, ex.Message, profileSetting.Value));
    return 1;
}
catch (HttpRequestException ex)
{
    Console.Error.WriteLine($"Network error: {ex.Message}");
    Console.Error.WriteLine(ErrorAdvisor.Advise(null, ex.GetType().Name, ex.Message, profileSetting.Value));
    return 1;
}

The supporting files (RunSettings.cs, CallerIdentity.cs, SetupReport.cs, ErrorAdvisor.cs) contain only pure logic, which is why they can be unit-tested without AWS.

Code explained line by line

  1. using Amazon.Runtime.CredentialManagement; โ€” brings in CredentialProfileStoreChain, which reads the shared config and credentials files.
  2. RunSettings.ParseArguments(args) โ€” parses --profile, --region, --mask-account, --skip-s3; unknown arguments return exit code 2 instead of a stack trace.
  3. RunSettings.ResolveProfile(...) โ€” picks the profile: --profile, then AWS_PROFILE, then learn-sandbox, and records where it came from so the report can show it.
  4. chain.TryGetProfile(...) โ€” loads the profile definition, including its region. If it does not exist, the app explains how to create it.
  5. chain.TryGetAWSCredentials(...) โ€” builds a credentials object for the profile. For an sso_session profile this is an SSOAWSCredentials; for an aws login profile, a login credentials object. Nothing is fetched from AWS yet.
  6. credentials is SSOAWSCredentials sso โ€” a C# type pattern. If it is an SSO profile, the app sets SupportsGettingNewToken = false so it fails clearly instead of opening a browser, and sets a ClientName without spaces (spaces cause a runtime exception).
  7. RunSettings.ResolveRegion(...) โ€” --region, AWS_REGION, AWS_DEFAULT_REGION, the profile's region, then us-east-1. Explicit Regions avoid surprises; in SDK v4, STS calls go to the Regional endpoint of the Region you choose.
  8. new AmazonSecurityTokenServiceClient(credentials, region) โ€” the STS client with explicit credentials and Region. using disposes the underlying HTTP resources.
  9. GetCallerIdentityAsync(...) โ€” the first network call. This is when the SDK exchanges your SSO token for role credentials. If the token is missing or expired, an AmazonClientException is thrown here.
  10. CallerIdentity.Parse(identity.Arn) โ€” splits the ARN and recognises root, IAM users, Identity Center roles (AWSReservedSSO_<permission set>_<suffix>) and the AWS Emulator account 000000000000.
  11. ListBucketsAsync(new ListBucketsRequest()) โ€” the first authorised call. IAM and SCPs decide whether it succeeds.
  12. buckets.Buckets?.Count ?? 0 โ€” SDK v4 returns null for empty collections (a breaking change from v3), so the null-conditional is required.
  13. new SetupReport(...) / report.Format() โ€” builds the checks and the text output; the logic is unit-tested.
  14. return report.Passed ? 0 : 1; โ€” non-zero exit codes let you use the app in scripts and CI.
  15. catch (AmazonServiceException ex) โ€” AWS answered with an error code (AccessDenied, ExpiredTokenโ€ฆ). ErrorAdvisor maps the code to a plain-language fix.
  16. catch (AmazonClientException ex) โ€” the SDK failed before AWS answered (for example, no valid SSO token). In SDK v4 both AmazonServiceException and AmazonClientException derive directly from System.Exception (checked by reflection against AWSSDK.Core 4.1.1.1), so you need both catch blocks; neither catches the other.
  17. catch (HttpRequestException ex) โ€” DNS, proxy or connectivity failures that never reached AWS.

Security considerations

  • No access keys in code, configuration, environment variables or the credentials file. The app relies only on a profile name.
  • The app never prints tokens or keys, and --mask-account hides the account ID for screenshots.
  • GetCallerIdentity cannot be blocked by IAM โ€” never use it as an authorisation check in your own systems; it only tells you who the caller is.
  • The [FAIL] on root and the [WARN] on stray environment keys turn good habits into automated checks.

โš  Learning shortcut โ€” not for production

The lab signs in as a person using SandboxAdmin. Production .NET services must never use personal SSO profiles: on AWS they get credentials from their compute role (ECS task role, Lambda execution role, EC2 instance profile) through the SDK's default chain, and CI/CD pipelines assume roles with OIDC. In those environments you would also remove the explicit profile loading and let the default chain resolve credentials.

Banking use case

"Harbour Bank" (fictional) ships a tiny whoami health endpoint in every internal .NET service, protected by staff authentication. It calls GetCallerIdentity and returns the account alias, role name and Region โ€” never the full ARN to non-admins. During incidents, the on-call engineer checks it first to confirm the service is running under the expected task role in the expected account, which has repeatedly caught deployments that accidentally used a shared role with broader permissions.

Common mistakes

  • Removing AWSSDK.SSO / AWSSDK.SSOOIDC because "nothing uses them" โ†’ no using references them โ†’ the SDK needs them at runtime for SSO profiles.
  • Forgetting -- before app arguments โ†’ dotnet run tries to interpret --profile itself โ†’ put -- before the app's arguments.
  • Treating GetCallerIdentity success as "I have permissions" โ†’ it needs none โ†’ the S3 call is the real permission test.
  • Iterating Buckets without a null check โ†’ SDK v4 returns null for empty lists โ†’ use ?. or AWSConfigs.InitializeCollections = true.
  • Running with the management profile โ†’ it works, but labs belong in the sandbox โ†’ always pass --profile learn-sandbox.

Troubleshooting

SymptomLikely causeFix
The AWS SDK could not make the request: ... followed by "Your sign-in session has expired or is missing"No valid SSO token: you ran aws sso logout, or the portal session expired (8 hours by default)aws sso login --sso-session cea (Path B: aws login --profile learn-sandbox)
No profile named 'learn-sandbx' was found ...Wrong profile name, or AWS_PROFILE points at a missing profileaws configure list-profiles; pass --profile learn-sandbox
AWS returned an error: AccessDenied - Access Denied on S3Permission set lacks s3:ListAllMyBuckets, or an SCP denies itCheck the permission set in IAM Identity Center; rerun with --skip-s3 to confirm identity works
Account ID is your management accountWrong profile (learn-management)Use learn-sandbox; never run labs in the management account
[FAIL] You are calling AWS as the ROOT USERA profile that uses root credentialsStop. Delete root access keys (Security credentials), use Identity Center
[WARN] AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY are setStray environment variablesRemove-Item Env:AWS_ACCESS_KEY_ID, Env:AWS_SECRET_ACCESS_KEY, Env:AWS_SESSION_TOKEN
AWS returned an error: InvalidClientTokenIdOld or fake static keys in a profile in the credentials fileRemove the keys from %USERPROFILE%\.aws\credentials (and delete them in IAM)
Runtime error about loading AWSSDK.SSO or AWSSDK.SSOOIDCPackages missingRestore the package references and rebuild
[INFO] Account 000000000000 means you are talking to AWS EmulatorAWS_ENDPOINT_URL set in this shellOpen a new shell without emulator variables
Network error: No such host is knownProxy, VPN, DNSCheck connectivity; corporate networks may need proxy settings

The exact text of SDK exception messages can vary between SDK versions; the advice line printed by the app is what to follow.

Cost and cleanup

Cost: free. STS GetCallerIdentity has no charge; one S3 ListBuckets request is a single request billed per thousand, effectively zero. The lab creates nothing.

Cleanup:

# End your session (deletes cached SSO tokens).
aws sso logout
# Optional: remove build output.
dotnet clean VerifySetup.slnx

Exercises

  • ๐ŸŸข Guided: Run the app with --profile learn-sandbox, then with --profile learn-management and --profile learn-billing. Record which account and permission set each reports, and which ones can list buckets.
  • ๐ŸŸก Challenge: In IAM Identity Center create a permission set NoS3 with an inline policy that allows nothing (an empty statement list is not allowed, so allow only sts:GetCallerIdentity). Assign it to the sandbox, add a learn-nos3 profile, and run the app with and without --skip-s3. Explain both results.
  • ๐Ÿ”ด Live problem: A colleague runs the lab and gets PASS, but the account ID is one you do not recognise and the principal is Assumed IAM role 'OrganizationAccountAccessRole'. They say "it passed, so it's fine." Investigate what their configuration probably looks like and what risk it carries.

Assignment

Add a tools/whoami/ folder to your learning-journal repository with a copy of this lab, extended with a --json option that prints the report as JSON (use System.Text.Json, add tests for it), and a short README explaining when you would run it.

Solutions

Knowledge check

Interview questions

  • "How does your .NET application get AWS credentials locally and in production?" โ€” Locally from a named Identity Center profile after aws sso login; in production from the compute role via the SDK default credential chain; in CI from an OIDC-assumed role. Never from stored keys.
  • "A service gets AccessDenied. What's your first step?" โ€” Confirm the identity with GetCallerIdentity (or the error's principal ARN), then check the identity policy, resource policy, permission boundary, SCP and, if encryption is involved, the KMS key policy.

Certification practice

Completion checklist

  • dotnet run --project src/VerifySetup -- --profile learn-sandbox prints Result : PASS
  • The account ID matches the sandbox account in the access portal
  • dotnet test --solution VerifySetup.slnx passes (31 tests)
  • I reproduced the expired-token, wrong-profile and stray-keys errors and fixed each
  • I ran aws sso logout at the end

Key takeaways

  • A named Identity Center profile plus aws sso login gives .NET code short-lived credentials with no keys on disk.
  • AWS SDK for .NET v4 needs AWSSDK.SSO and AWSSDK.SSOOIDC at runtime for SSO profiles (and AWSSDK.Signin for aws login profiles).
  • GetCallerIdentity answers "who am I?" for free and without permissions; an S3 call tests "am I allowed?".
  • SDK v4 returns null for empty collections โ€” always null-check.
  • Personal profiles are for development only; deployed services use compute roles.

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