IAM Identity Center, MFA and temporary credentials
Give people short-lived, MFA-protected access through IAM Identity Center permission sets, and make applications assume roles safely with STS — external IDs, source identity, session tags and the one-hour role-chaining limit — from the CLI and from C#.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.SecurityToken 4.1.0.2) · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-17.
Learning objectives
By the end of this lesson you can:
- Explain how IAM Identity Center turns a user's group membership into a short-lived role session in an AWS account, using permission sets and account assignments.
- Configure MFA correctly for the root user, Identity Center users and (by exception) IAM users, and prefer phishing-resistant passkeys and security keys.
- Configure the AWS CLI with an
sso-sessionand thelearn-sandboxprofile, and explain how the AWS SDK for .NET finds credentials. - Call STS AssumeRole from C# with an external ID, a source identity and session tags, and explain the one-hour cap on role chaining.
- Explain the confused deputy problem and how
sts:ExternalId,aws:SourceArnandaws:SourceAccountprevent it.
Prerequisites
- Secure your AWS account — you enabled Identity Center and have the
learn-sandboxprofile - IAM in depth — roles, trust policies and permissions policies
- Least privilege in practice — helpful for the permission-set design exercise
- Tools: AWS CLI v2, .NET 10 SDK
Why this matters in banking
A Harbourline production-support engineer needs to look at a failing payments queue at 02:00. In the old world they had a standing domain-admin account "for emergencies". An attacker who phished that password would have had it too.
The target model is different:
- The engineer signs in once through the corporate identity provider with a phishing-resistant MFA method.
- They pick the Payments-Prod-ReadOnly permission set, which gives a one-hour session.
- If they need to change something, they request Payments-Prod-Operator, which is assigned only for the duration of an approved incident ticket.
- Every API call they make is recorded in CloudTrail with their identity, not a shared account.
- Applications never hold human credentials; they assume roles with their own trust rules.
Regulators expect strong authentication, least privilege and traceability for privileged access. AWS provides the mechanisms; Harbourline's identity governance — joiner/mover/leaver processes, approval workflows, access reviews — remains its own responsibility (security in the cloud).
The idea in plain language
Temporary credentials are the heart of modern AWS access. Instead of a password or access key that works forever, you exchange proof of who you are for a credential set that expires — usually within an hour.
- AWS STS (Security Token Service) is the service that issues those credentials. The main call is
AssumeRole: "I am principal X; let me act as role Y for N minutes." - IAM Identity Center is the front door for people. It holds (or connects to) the user directory, enforces MFA, shows each user a portal of the accounts and roles they may use, and calls STS for them behind the scenes.
- A permission set is a template of policies. When you assign a group and a permission set to an account, Identity Center creates a matching IAM role in that account, named
AWSReservedSSO_<PermissionSetName>_<suffix>.
Analogy: Identity Center is the bank's staff reception desk. You show your staff card and PIN (password and MFA). Reception checks the rota (assignments) and gives you a visitor badge for a specific floor (account) with specific rights (permission set). The badge expires at the end of your shift (session duration). STS is the badge printer; anyone authorised — reception, a manager, or an automated system — can ask it for a badge, but only for doors the badge rules allow.
What problem each service solves
| Service / feature | Problem it solves | Limits and sharp edges |
|---|---|---|
| IAM Identity Center (organisation instance) | One place for workforce access to many accounts and applications | Must be enabled in the management account (or delegated admin); one home Region; free |
| Permission set | Consistent roles across accounts without hand-writing IAM in each | Session duration 1–12 hours (default 1 hour); changes reprovision every assigned account; customer managed policy references must exist by name in every target account |
| MFA in Identity Center | Second factor at sign-in | On by default for the Identity Center directory; when you use an external IdP (for example Entra ID), MFA is enforced by that IdP, not by Identity Center |
| STS AssumeRole | Exchange one identity for a time-limited role session | 15 minutes to the role's maximum session duration (1–12 hours); role chaining is capped at 1 hour; default STS request quota 600 requests per second per account per Region |
| External ID | Stops a third-party service being tricked into using your role for someone else | Only for cross-account roles assumed by a third party; the value comes from the third party |
| Source identity | Records who is really behind a role session, and cannot be changed later in the chain | Requires sts:SetSourceIdentity in the trust policy; 2–256 characters |
| Session tags | Attributes (team, cost centre) attached to a session for ABAC and audit | Up to 50 tags; sts:TagSession must be allowed; not available through console role switching |
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Entra ID enterprise application for Azure portal sign-in | IAM Identity Center with Entra ID as the external IdP (SAML for sign-in, SCIM for provisioning) | AWS access is per account and per permission set; the portal lists account/role pairs |
| Azure RBAC role assignment to a group at a subscription scope | Account assignment: group + permission set + account | Creates a real IAM role in the account; nothing to configure per account by hand |
| Entra Conditional Access requiring MFA | Identity Center MFA settings, or Conditional Access at Entra ID when federated | When federated, Conditional Access is where MFA and device policy live |
| Privileged Identity Management (PIM) just-in-time activation | Separate high-privilege permission sets with short sessions, assigned temporarily (manual or via an approval workflow) | No built-in PIM equivalent; AWS publishes an open-source temporary elevated access solution ⚠ VERIFY current name and status |
| Managed identity token from IMDS | Role credentials from the ECS/EKS/EC2 credential endpoints | Same concept; the AWS SDK refreshes them automatically |
az login | aws sso login --profile learn-sandbox | The CLI caches an SSO token and fetches role credentials per profile |
DefaultAzureCredential | AWS SDK default credential chain | Order differs; in .NET v4: explicit, environment, web identity, profile, container, EC2 metadata |
| Azure Lighthouse (delegated access for a service provider) | Cross-account role with an external ID | The external ID protects against the confused deputy problem |
Architecture
How a person gets credentials:
How an application assumes a role in another account, with the confused-deputy defences:
Security-boundary view: the trust policy on each role is the gate between accounts. Identity Center roles trust only the Identity Center SAML provider. Vendor roles trust the vendor's account and require a vendor-issued external ID. Internal cross-account roles trust specific role ARNs and require a source identity so CloudTrail always shows which human or job started the chain.
Credentials in depth
Session duration rules
| How the session is created | Minimum | Maximum | Default |
|---|---|---|---|
| Identity Center permission set (console or CLI) | 1 hour | 12 hours | 1 hour |
AssumeRole from a user or a fresh session | 15 minutes | Role's maximum session duration (1–12 hours) | 1 hour |
AssumeRole using credentials from another role (role chaining) | 15 minutes | 1 hour, whatever the role's setting | 1 hour |
| EC2 instance profile, ECS task role, Lambda execution role | Managed by the service, refreshed automatically | — | — |
Role chaining catches people out. Your SSO session is a role session, so when you use it to call AssumeRole on another role, that is chaining — requesting DurationSeconds = 7200 fails even if the target role allows 12 hours.
MFA: what to use where
| Identity | MFA rule at Harbourline | Notes |
|---|---|---|
| Root user (every account) | Mandatory — AWS enforces MFA for root users of all account types | Prefer a passkey or FIDO2 security key; up to 8 MFA devices per root user; or remove member-account root credentials with centralised root access |
| Identity Center directory users | Mandatory, every sign-in, FIDO2 preferred | Each user can register up to 8 devices (2 authenticator apps, 6 FIDO authenticators) |
| Users federated from Entra ID / AD FS | Enforced at the IdP (Conditional Access) | Identity Center MFA does not apply to external IdP users |
| IAM users (exceptions only) | MFA for console; for API use, GetSessionToken with MFA and policies that require it | Requests signed with plain long-lived keys carry no MFA context |
Phishing-resistant MFA (passkeys bound to the website origin, hardware security keys) stops the real-time phishing proxies that defeat SMS and one-time codes. For production access at a bank, it should be the only accepted method.
Confused deputy, source identity and session tags
- Confused deputy (cross-account): a vendor that serves many customers could be tricked by customer B into using customer A's role ARN. The external ID in A's trust policy, issued by the vendor uniquely per customer, makes that impossible. You never invent the external ID yourself.
- Confused deputy (cross-service): when an AWS service writes into your resources, restrict it with
aws:SourceArn,aws:SourceAccountoraws:SourceOrgIDin the resource policy. - Source identity: a value set at the first
AssumeRole(for example the engineer's email) that persists through every subsequent chained role and cannot be changed. CloudTrail shows it insourceIdentity, so "who really did this?" is answerable even through shared roles. - Session tags: key-value attributes on a session (
team=payments,ticket=INC-20341) usable in policies asaws:PrincipalTag/.... Mark them transitive to carry them along a role chain.
Step-by-step implementation
Check your CLI SSO configuration
Open %USERPROFILE%\.aws\config. It should contain an sso-session block and a profile that references it (the start URL is shown in Console → IAM Identity Center → Dashboard → AWS access portal URL):
[sso-session harbourline]
sso_start_url = https://d-1234567890.awsapps.com/start
sso_region = us-east-1
sso_registration_scopes = sso:account:access
[profile learn-sandbox]
sso_session = harbourline
sso_account_id = 111122223333
sso_role_name = SandboxAdmin
region = us-east-1
output = jsonThen aws sso login --profile learn-sandbox. The browser opens, you complete MFA, and the CLI caches a token. aws configure sso creates the same blocks interactively.
Create a read-only permission set with a short session
Create HlSecurityAuditor with the AWS managed SecurityAudit and ViewOnlyAccess policies and a one-hour session, and assign it to your learner group on the sandbox account (CLI below). Add a second profile learn-sandbox-audit with sso_role_name = HlSecurityAuditor.
Create a role to assume, with strict trust
Create hl-m05-auditor in the sandbox (IaC below). Its trust policy allows only your SandboxAdmin SSO role, requires a source identity that looks like an email address, and only allows the session tag key ticket.
Assume it from the CLI
Use the assume-role command with --source-identity and --tags, then decode what CloudTrail recorded.
Assume it from C#
Run the console app in Complete code. It shows the expiry time, the assumed-role ARN, and what happens when you ask for two hours through a role chain.
AWS Console instructions
- Console → IAM Identity Center → Settings → Authentication → Multi-factor authentication → Configure: choose when to prompt (every sign-in is the bank-grade choice), which MFA types are allowed (prefer Security keys and built-in authenticators), and what happens if a user has no device (require registration at sign-in).
- Console → IAM Identity Center → Multi-account permissions → Permission sets → Create permission set → Custom permission set → attach
SecurityAuditandViewOnlyAccess→ nameHlSecurityAuditor→ Session duration: 1 hour → add tags. - Console → IAM Identity Center → AWS accounts → select the sandbox account → Assign users or groups → choose
cea-learners→ chooseHlSecurityAuditor→ Submit. Identity Center provisions the role in the account. - Console → IAM → Roles in the sandbox now shows
AWSReservedSSO_HlSecurityAuditor_<suffix>. Do not edit it by hand — changes are overwritten on the next provisioning. - Console → (account menu) → Security credentials as root: register a passkey or security key as MFA.
AWS CLI
# Identity Center instance and identity store IDs (run with a management/delegated-admin profile).
aws sso-admin list-instances --profile cea-management \
--query "Instances[0].{Instance:InstanceArn,Store:IdentityStoreId}"
INSTANCE_ARN=arn:aws:sso:::instance/ssoins-1234567890abcdef
STORE_ID=d-1234567890
# Create a permission set with a 1-hour session (ISO 8601 duration).
PS_ARN=$(aws sso-admin create-permission-set --profile cea-management \
--instance-arn "$INSTANCE_ARN" --name HlSecurityAuditor \
--description "Read-only security audit for Harbourline workload accounts" \
--session-duration PT1H \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m05-identity Key=Environment,Value=learn Key=Owner,Value=alex \
--query PermissionSet.PermissionSetArn --output text)
# Attach AWS managed policies to the permission set.
aws sso-admin attach-managed-policy-to-permission-set --profile cea-management \
--instance-arn "$INSTANCE_ARN" --permission-set-arn "$PS_ARN" \
--managed-policy-arn arn:aws:iam::aws:policy/SecurityAudit
aws sso-admin attach-managed-policy-to-permission-set --profile cea-management \
--instance-arn "$INSTANCE_ARN" --permission-set-arn "$PS_ARN" \
--managed-policy-arn arn:aws:iam::aws:policy/job-function/ViewOnlyAccess
# Look up the group and assign group + permission set to the sandbox account.
GROUP_ID=$(aws identitystore list-groups --profile cea-management --identity-store-id "$STORE_ID" \
--filters AttributePath=DisplayName,AttributeValue=cea-learners --query "Groups[0].GroupId" --output text)
aws sso-admin create-account-assignment --profile cea-management \
--instance-arn "$INSTANCE_ARN" --permission-set-arn "$PS_ARN" \
--target-type AWS_ACCOUNT --target-id 111122223333 \
--principal-type GROUP --principal-id "$GROUP_ID"
# Sign in with the new permission set.
aws configure set profile.learn-sandbox-audit.sso_session harbourline
aws configure set profile.learn-sandbox-audit.sso_account_id 111122223333
aws configure set profile.learn-sandbox-audit.sso_role_name HlSecurityAuditor
aws configure set profile.learn-sandbox-audit.region us-east-1
aws sso login --profile learn-sandbox-audit
aws sts get-caller-identity --profile learn-sandbox-audit
# Assume hl-m05-auditor from the SandboxAdmin session (role chaining: max 3600 s).
aws sts assume-role --profile learn-sandbox \
--role-arn arn:aws:iam::111122223333:role/hl-m05-auditor \
--role-session-name alex-INC-20341 \
--source-identity alex.learner@example.com \
--tags Key=ticket,Value=INC-20341 \
--duration-seconds 3600 \
--query "{Expires:Credentials.Expiration,Arn:AssumedRoleUser.Arn}"
# Prove the chaining cap: this fails with a ValidationError about the 1 hour limit.
aws sts assume-role --profile learn-sandbox \
--role-arn arn:aws:iam::111122223333:role/hl-m05-auditor \
--role-session-name alex-too-long --source-identity alex.learner@example.com \
--duration-seconds 7200cea-management is the profile for the management account from Module 0. In production, delegate Identity Center administration to a dedicated identity account rather than using the management account day to day.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.SSO;
using Constructs;
namespace Harbourline.Security.Infra;
/// <summary>Deployed to the sandbox account: the role that engineers chain into.</summary>
public sealed class AuditorRoleStack : Stack
{
public AuditorRoleStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
{
var ssoAdminRolePattern =
$"arn:aws:iam::{Account}:role/aws-reserved/sso.amazonaws.com/*AWSReservedSSO_SandboxAdmin_*";
var role = new Role(this, "Auditor", new RoleProps
{
RoleName = "hl-m05-auditor",
MaxSessionDuration = Duration.Hours(1),
AssumedBy = new AccountPrincipal(Account).WithConditions(new Dictionary<string, object>
{
["ArnLike"] = new Dictionary<string, object> { ["aws:PrincipalArn"] = ssoAdminRolePattern },
["StringLike"] = new Dictionary<string, object> { ["sts:SourceIdentity"] = "*@example.com" }
}),
ManagedPolicies = [ManagedPolicy.FromAwsManagedPolicyName("SecurityAudit")]
});
// The trust policy must also allow setting source identity and the 'ticket' session tag.
role.AssumeRolePolicy!.AddStatements(new PolicyStatement(new PolicyStatementProps
{
Sid = "AllowSourceIdentityAndTicketTag",
Principals = [new AccountPrincipal(Account)],
Actions = ["sts:SetSourceIdentity", "sts:TagSession"],
Conditions = new Dictionary<string, object>
{
["ArnLike"] = new Dictionary<string, object> { ["aws:PrincipalArn"] = ssoAdminRolePattern },
["ForAllValues:StringEquals"] = new Dictionary<string, object> { ["aws:TagKeys"] = new[] { "ticket" } }
}
}));
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m05-identity");
Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
Amazon.CDK.Tags.Of(this).Add("Owner", "alex");
}
}
/// <summary>Deployed to the management (or delegated identity) account.</summary>
public sealed class PermissionSetStack : Stack
{
public PermissionSetStack(Construct scope, string id, string instanceArn, string groupId, string targetAccountId,
IStackProps? props = null) : base(scope, id, props)
{
var permissionSet = new CfnPermissionSet(this, "HlSecurityAuditor", new CfnPermissionSetProps
{
InstanceArn = instanceArn,
Name = "HlSecurityAuditor",
Description = "Read-only security audit for Harbourline workload accounts",
SessionDuration = "PT1H",
ManagedPolicies = new[]
{
"arn:aws:iam::aws:policy/SecurityAudit",
"arn:aws:iam::aws:policy/job-function/ViewOnlyAccess"
}
});
_ = new CfnAssignment(this, "LearnersToSandbox", new CfnAssignmentProps
{
InstanceArn = instanceArn,
PermissionSetArn = permissionSet.AttrPermissionSetArn,
PrincipalType = "GROUP",
PrincipalId = groupId,
TargetType = "AWS_ACCOUNT",
TargetId = targetAccountId
});
}
}Complete code
The console app assumes hl-m05-auditor with a source identity and a ticket tag, uses the temporary credentials, and demonstrates the chaining limit.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RootNamespace>Harbourline.Security.AssumeRoleDemo</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.SecurityToken" Version="4.1.0.2" />
<!-- Runtime requirements for resolving IAM Identity Center (SSO) profiles. -->
<PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
</ItemGroup>
</Project>using Amazon;
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
const string RoleName = "hl-m05-auditor";
var profileName = Environment.GetEnvironmentVariable("AWS_PROFILE") ?? "learn-sandbox";
var engineer = Environment.GetEnvironmentVariable("HL_ENGINEER_EMAIL") ?? "alex.learner@example.com";
var ticket = args.FirstOrDefault() ?? "INC-20341";
// 1. Source credentials: the engineer's SSO session from the named profile.
if (!new CredentialProfileStoreChain().TryGetAWSCredentials(profileName, out var sourceCredentials))
{
Console.Error.WriteLine($"Profile '{profileName}' not found. Run: aws sso login --profile {profileName}");
return 2;
}
using var sts = new AmazonSecurityTokenServiceClient(sourceCredentials, RegionEndpoint.USEast1);
var me = await sts.GetCallerIdentityAsync(new GetCallerIdentityRequest());
Console.WriteLine($"Source identity : {me.Arn}");
var roleArn = $"arn:aws:iam::{me.Account}:role/{RoleName}";
// 2. Assume the auditor role: 15 minutes, who-did-it recorded, ticket attached.
var response = await sts.AssumeRoleAsync(new AssumeRoleRequest
{
RoleArn = roleArn,
RoleSessionName = $"{engineer.Split('@')[0]}-{ticket}", // 2-64 chars, shows in the session ARN
SourceIdentity = engineer, // immutable for the whole chain
Tags = [new Tag { Key = "ticket", Value = ticket }], // available as aws:PrincipalTag/ticket
DurationSeconds = 900
});
var c = response.Credentials;
Console.WriteLine($"Assumed role : {response.AssumedRoleUser.Arn}");
Console.WriteLine($"Key id : {c.AccessKeyId[..4]}...{c.AccessKeyId[^4..]} (ASIA = temporary)");
Console.WriteLine($"Expires (UTC) : {c.Expiration:u}");
// 3. Use the temporary credentials for a second client.
var session = new SessionAWSCredentials(c.AccessKeyId, c.SecretAccessKey, c.SessionToken);
using var auditorSts = new AmazonSecurityTokenServiceClient(session, RegionEndpoint.USEast1);
var auditor = await auditorSts.GetCallerIdentityAsync(new GetCallerIdentityRequest());
Console.WriteLine($"Now acting as : {auditor.Arn}");
// 4. Role chaining is capped at one hour, whatever the role's MaxSessionDuration says.
try
{
await sts.AssumeRoleAsync(new AssumeRoleRequest
{
RoleArn = roleArn,
RoleSessionName = "chaining-limit-demo",
SourceIdentity = engineer,
DurationSeconds = 7200
});
Console.WriteLine("Unexpected: a two-hour chained session was issued.");
}
catch (AmazonSecurityTokenServiceException ex) when (ex.ErrorCode == "ValidationError")
{
Console.WriteLine($"Chaining limit : {ex.Message}");
}
return 0;Expected output (values will differ):
Source identity : arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_SandboxAdmin_0123456789abcdef/alex.learner
Assumed role : arn:aws:sts::111122223333:assumed-role/hl-m05-auditor/alex.learner-INC-20341
Key id : ASIA...WXYZ (ASIA = temporary)
Expires (UTC) : 2026-11-17 10:47:03Z
Now acting as : arn:aws:sts::111122223333:assumed-role/hl-m05-auditor/alex.learner-INC-20341
Chaining limit : The requested DurationSeconds exceeds the 1 hour session limit for roles assumed by role chaining.The exact error wording is AWS's and may change; the error code is what to rely on.
The same idea in an ASP.NET Core service
Applications should not call AssumeRole for their own identity — the platform gives them one. Register clients with the default chain and let ECS, Lambda or EC2 supply role credentials:
using Amazon.DynamoDBv2;
using Amazon.Extensions.NETCore.Setup;
var builder = WebApplication.CreateBuilder(args);
// Locally: AWS_PROFILE=learn-sandbox. On ECS: the task role. No secrets in configuration.
builder.Services.AddDefaultAWSOptions(builder.Configuration.GetAWSOptions());
builder.Services.AddAWSService<IAmazonDynamoDB>();
var app = builder.Build();
app.MapGet("/health", () => Results.Ok());
app.Run();GetAWSOptions() reads an optional "AWS" section (Profile, Region) from configuration; leave Profile out of production configuration so the container credential provider is used.
Code explained line by line
HL_ENGINEER_EMAIL— in a real tool, read the signed-in user's identity rather than an environment variable; here it keeps the demo simple.CredentialProfileStoreChain().TryGetAWSCredentials(profileName, ...)— resolves the SSO profile. If the cached SSO token has expired the call to STS will fail; runaws sso loginagain.GetCallerIdentityAsync— needs no permissions and is the fastest way to prove which principal you are. It also gives the account ID for building the role ARN instead of hard-coding it.RoleSessionName— appears at the end of the assumed-role ARN and in CloudTrail. Use something meaningful (person plus ticket) rather than a GUID.SourceIdentity = engineer— requiressts:SetSourceIdentityin the target role's trust policy. Once set, it travels with every chained session and cannot be replaced.Tags = [new Tag { ... }]— session tags; requiressts:TagSession. The trust policy restricts which keys may be passed.DurationSeconds = 900— the minimum. Ask for what the task needs.c.AccessKeyId[..4]— temporary keys start withASIA; long-lived user keys start withAKIA. SpottingAKIAin logs or code is an instant red flag.SessionAWSCredentials— wraps the three values. It does not refresh; when the session expires, assume again. For long-running processes use a refreshing provider or let the hosting platform supply credentials.DurationSeconds = 7200insidetry— fails withValidationErrorbecause the caller is itself a role session.catch ... when (ex.ErrorCode == "ValidationError")— filter on the error code, not on message text.
⚠ Learning shortcut — not for production
The demo prints a masked key ID and runs from a developer laptop. In production: never log any part of the secret or session token; do not build tools that chain roles for humans when an Identity Center permission set would do; and put cross-account automation in pipelines that assume roles through OIDC federation (for example GitHub Actions to an IAM role) rather than holding any long-lived key. For privileged human access, assign high-privilege permission sets only for the duration of an approved change or incident and review the assignment log.
Security considerations
- Short sessions for privileged permission sets. One hour for operator and admin access; longer only for low-risk read-only work.
- Separate permission sets by risk, not one "Developer" set: read-only, operator, break-glass. Each one maps to a different approval path.
- Phishing-resistant MFA everywhere. If Entra ID is the IdP, enforce it with Conditional Access; Identity Center will not add MFA on top of an external IdP.
- Trust policies are your cross-account firewall. Name specific role ARNs (or use
aws:PrincipalArnpatterns), requirests:ExternalIdfor third parties, require a source identity for internal chains, and never trust"AWS": "*"without strong conditions. - Do not rely on
aws:MultiFactorAuthPresentto prove that an Identity Center user used MFA — enforce MFA at sign-in instead. Whether the key is set for Identity Center role sessions should be tested in your environment ⚠ VERIFY. - Monitor STS. Alert on
AssumeRoleinto sensitive roles, onGetFederationToken(rarely legitimate), and on access keys startingAKIAbeing used at all — see CloudTrail for banks and Incident response. - Break-glass: keep at least one emergency path that does not depend on the external IdP (for example a sealed Identity Center directory user or the management account root with hardware MFA), tested twice a year.
Banking use case
Harbourline's access model for the Payments production account:
| Permission set | Who | Session | How granted |
|---|---|---|---|
Payments-Prod-ReadOnly | Payments engineers | 4 hours | Permanent assignment via Entra ID group |
Payments-Prod-Operator | On-call engineer | 1 hour | Temporary assignment linked to an incident or change ticket; removed afterwards |
Payments-Prod-BreakGlass | Two named senior engineers | 1 hour | Sealed procedure, dual authorisation, alarm on every use |
Security-Audit | Security and internal audit | 4 hours | Permanent, read-only, across all accounts |
A vendor that monitors the card-processing platform gets a single role with ViewOnlyAccess, trust limited to the vendor's account and a vendor-issued external ID, and a quarterly review. CloudTrail shows the source identity on every chained session, which answers the auditor's "who" question without a shared account. This design supports segregation of duties (Federation and segregation of duties), but whether it meets a specific regulation's strong-authentication or privileged-access requirements is for Harbourline's risk and compliance teams to decide.
Common mistakes
- Requesting long sessions through a role chain →
ValidationError→ chained sessions are capped at 1 hour; assume directly from the original identity or accept the hour. - Editing
AWSReservedSSO_*roles in IAM → changes vanish at the next reprovisioning → change the permission set instead. - Customer managed policy reference missing in one account → provisioning fails for that account → deploy the policy to all target accounts first (StackSets or your IaC pipeline).
- Inventing your own external ID for a vendor → it does not prevent the confused deputy → the vendor must generate a unique ID per customer.
- Assuming MFA is enforced because Identity Center shows MFA settings → with an external IdP those settings do not apply → enforce at the IdP.
- Missing
sts:SetSourceIdentityorsts:TagSessionin the trust policy →AccessDeniedonAssumeRoleeven thoughsts:AssumeRoleis allowed.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Error loading SSO Token: Token for ... does not exist | Never logged in, or token expired | aws sso login --profile learn-sandbox |
C# app: Profile ... not found or SSO assembly error | Profile name typo, or AWSSDK.SSO/SSOOIDC not referenced | Check %USERPROFILE%\.aws\config; add the packages |
AccessDenied ... not authorized to perform: sts:AssumeRole on resource | Trust policy does not match your principal, or your identity policy does not allow sts:AssumeRole | Compare get-caller-identity ARN with the trust policy aws:PrincipalArn pattern |
AccessDenied only when passing --source-identity or --tags | sts:SetSourceIdentity / sts:TagSession not allowed, or tag key not permitted | Add the action to the trust policy; check aws:TagKeys condition |
ValidationError ... 1 hour session limit ... role chaining | Chained session asked for more than 3600 seconds | Request 3600 or less |
ExpiredToken mid-run in a long job | SessionAWSCredentials does not refresh | Re-assume before expiry or use platform-provided role credentials |
| Permission set assignment stuck in In progress / Failed | Referenced customer managed policy or boundary missing in target account | Create it in the account, then reprovision |
Cost and cleanup
IAM Identity Center, permission sets, account assignments, STS and IAM roles are free. This lesson creates no billable resources.
# Sandbox account: remove the demo role.
aws iam detach-role-policy --role-name hl-m05-auditor \
--policy-arn arn:aws:iam::aws:policy/SecurityAudit --profile learn-sandbox
aws iam delete-role --role-name hl-m05-auditor --profile learn-sandbox
# Management account: remove the assignment, then the permission set (keep it if you want the audit profile).
aws sso-admin delete-account-assignment --profile cea-management \
--instance-arn "$INSTANCE_ARN" --permission-set-arn "$PS_ARN" \
--target-type AWS_ACCOUNT --target-id 111122223333 \
--principal-type GROUP --principal-id "$GROUP_ID"
aws sso-admin delete-permission-set --profile cea-management \
--instance-arn "$INSTANCE_ARN" --permission-set-arn "$PS_ARN"
# Confirm no demo roles remain.
aws iam list-roles --profile learn-sandbox --query "Roles[?starts_with(RoleName,'hl-m05')].RoleName"Deleting the assignment can take a minute to deprovision the role in the sandbox; delete the permission set after the assignment shows as removed.
Exercises
- 🟢 Guided: Create the
HlSecurityAuditorpermission set and thelearn-sandbox-auditprofile, sign in with it, and confirm thataws s3 mb s3://hl-m05-should-fail-<yourname>is denied whileaws iam list-rolesworks. - 🟡 Challenge: Make the C# demo chain a second time: from
hl-m05-auditorinto a new rolehl-m05-auditor-2with a transitivetickettag. Prove in CloudTrail (Event history,AssumeRoleevents) that the source identity is the same in both hops and that the ticket tag was carried over. - 🔴 Live problem: A managed security service provider (MSSP) asks Harbourline to "create an IAM user with ReadOnlyAccess in each of our 40 accounts and email us the keys". Design the alternative, including what you need from the MSSP, the trust policy, how you would roll it out to 40 accounts, and how you will review it.
Assignment
Write docs/access-model.md for your portfolio repository: Harbourline's permission-set catalogue (name, policies, session duration, who, approval path), the MFA standard for each identity type, the break-glass procedure, and the trust-policy templates for vendor and internal cross-account roles. Include the C# demo's output as an appendix showing source identity in action.
Solutions
aws sso login --profile learn-sandbox-audit
aws sts get-caller-identity --profile learn-sandbox-audit # ...assumed-role/AWSReservedSSO_HlSecurityAuditor_...
aws iam list-roles --profile learn-sandbox-audit --query "length(Roles)" # works: SecurityAudit includes iam:List*
aws s3 mb s3://hl-m05-should-fail-alex --profile learn-sandbox-audit # make_bucket failed: AccessDeniedWhy: SecurityAudit and ViewOnlyAccess grant read and list actions only. Seeing the denial yourself builds confidence that the auditor role cannot change anything — the property you will describe to an auditor.
In the first AssumeRole, add TransitiveTagKeys = ["ticket"]. Then use the first session's credentials to assume the second role, without passing tags or source identity:
var hop2 = await auditorSts.AssumeRoleAsync(new AssumeRoleRequest
{
RoleArn = $"arn:aws:iam::{me.Account}:role/hl-m05-auditor-2",
RoleSessionName = "hop2",
DurationSeconds = 900
});The trust policy of hl-m05-auditor-2 must trust arn:aws:iam::<account>:role/hl-m05-auditor and allow sts:AssumeRole, sts:SetSourceIdentity and sts:TagSession (the transitive tag and inherited source identity count as being set). In CloudTrail, both AssumeRole events show sourceIdentity: alex.learner@example.com; the second event's request shows the inherited tag.
Why: transitive tags and source identity are what make multi-hop automation auditable. Without them the second hop looks like "role hl-m05-auditor did it", which is not a person.
Decline IAM users and emailed keys (long-lived secrets in email is an incident in itself). Instead:
- Ask the MSSP for its AWS account ID and a unique external ID for Harbourline.
- Create one role
hl-mssp-readonlyper account withViewOnlyAccess(orSecurityAudit, whichever matches the contract),MaxSessionDuration1 hour, and a trust policy allowing only the MSSP account withsts:ExternalIdequal to their value. - Roll out with CloudFormation StackSets (service-managed, targeting the relevant OUs) or Account Factory customisation, so new accounts get it automatically.
- Add an SCP or permissions boundary preventing the role from being modified except by the platform pipeline.
- Alert on
AssumeRoleinto the role from unexpected source IPs; review usage quarterly; record it in the third-party risk register (Operational resilience and third-party risk).
Why: this gives the vendor exactly the access the contract allows, with no secret to leak, protection from the confused deputy, central revocation (delete the stack set instance) and evidence for outsourcing oversight.
Knowledge check
Answer: An IAM role named AWSReservedSSO_<PermissionSetName>_<suffix> under the path /aws-reserved/sso.amazonaws.com/, with the permission set's policies and a trust policy for the Identity Center SAML provider. Users who are assigned can obtain sessions for it.
Answer: It fails. Using one role's credentials to assume another is role chaining, which is capped at one hour regardless of the target role's maximum session duration.
Answer: The cross-account confused deputy: a third party serving many customers being tricked into using one customer's role on behalf of another. The third party generates a unique external ID per customer; the customer puts it in the role's trust policy.
Answer: Source identity is set once and persists unchanged through every chained session; it requires sts:SetSourceIdentity. The session name can be different at each hop and is chosen by whoever calls AssumeRole.
Answer: In Entra ID (for example Conditional Access). Identity Center's MFA settings apply to its own directory, not to users authenticated by an external IdP.
Interview questions
- "How do you give engineers just-in-time admin access on AWS?" — Separate high-privilege permission sets with one-hour sessions; assign them only for an approved ticket (manually or through an approval workflow), with source identity and CloudTrail alerts; remove the assignment afterwards; review the history.
- "What is role chaining and what are its limits?" — Assuming a role with credentials from another role. The session is capped at one hour; transitive session tags and source identity can carry context across the chain.
- "Explain the confused deputy problem in AWS." — A more-privileged service is tricked into acting for someone who should not have access. Defend cross-account with external IDs and cross-service with
aws:SourceArn/aws:SourceAccount/aws:SourceOrgID. - "How does an ASP.NET Core app on ECS get AWS credentials?" — From the ECS task role through the container credential provider; the SDK's default chain finds it automatically. No keys in configuration.
Certification practice
A bank engages a cost-optimisation vendor that needs read-only access to billing data in the bank's management account. The vendor serves hundreds of customers from one AWS account. Which approach is MOST secure?
A. Create an IAM user for the vendor with ReadOnlyAccess and share the access keys through an encrypted email.
B. Create an IAM role trusting the vendor's account, with a condition requiring the vendor-provided unique external ID, and attach a billing read-only policy.
C. Create an IAM role trusting "AWS": "*" with a condition on the vendor's source IP range.
D. Invite the vendor's users to the bank's IAM Identity Center with the ViewOnlyAccess permission set.
Answer: B. A role with an external ID gives temporary credentials and prevents the confused deputy problem. A uses long-lived keys. C trusts everyone and relies on IP addresses that can change and do not identify the vendor's customer context. D gives individual vendor staff identities in the bank's workforce directory, which is harder to govern and is not how a multi-customer SaaS tool authenticates.
Several automation jobs share an IAM role in a production account. Auditors require that every API call made with the role can be attributed to the individual engineer who started the job, even when the job assumes further roles. What should the security engineer configure?
A. Require each job to set a unique role session name.
B. Require a source identity in the role's trust policy (sts:SetSourceIdentity with a condition on sts:SourceIdentity) and have jobs pass the engineer's identity when they first assume the role.
C. Tag the role with the engineer's name.
D. Enable CloudTrail data events for all S3 buckets.
Answer: B. Source identity is set once, cannot be changed and persists across role chaining, and CloudTrail records it on every call. Session names (A) can be changed at each hop. Role tags (C) are static and shared by all users. Data events (D) add detail but do not identify the engineer.
A company with 30 AWS accounts uses Microsoft Entra ID. It wants engineers to sign in with their corporate credentials, enforce MFA, and give different access in development and production accounts with minimal ongoing administration. What should a solutions architect recommend?
A. Create IAM users in each account and synchronise passwords from Entra ID with a script. B. Configure IAM Identity Center with Entra ID as the external identity provider and SCIM provisioning, enforce MFA in Entra ID, and assign groups to permission sets per account. C. Create a SAML identity provider in each of the 30 accounts and maintain roles in each manually. D. Use Amazon Cognito user pools federated with Entra ID.
Answer: B. Identity Center centralises workforce access across accounts, SCIM keeps users and groups in sync, and MFA is enforced at the IdP. A creates long-lived identities. C works but multiplies administration by 30. Cognito (D) is for customer-facing applications.
Completion checklist
- My
learn-sandboxprofile uses ansso-sessionand I can sign in with MFA - I created a permission set with a one-hour session and assigned it to a group
- I assumed a role with a source identity and a session tag from the CLI and from C#
- I saw the role-chaining limit fail with my own eyes
- I can explain the confused deputy problem and the external ID
- I deleted the demo role and (optionally) the permission set
Key takeaways
- People get access through IAM Identity Center: group + permission set + account = a short-lived role session, with MFA at sign-in (or at the external IdP).
- STS AssumeRole issues temporary credentials; role chaining is capped at one hour.
- External IDs stop vendors being confused deputies; source identity makes chained sessions attributable; session tags carry attributes for ABAC.
- Applications never call STS for their own identity — the platform supplies role credentials and the .NET SDK's default chain finds them.
- AWS provides the identity mechanisms; Harbourline owns the access model, approvals, reviews and evidence.
Further reading
- Set session duration for AWS accounts (IAM Identity Center)
- MFA for Identity Center directory users
- Methods to assume a role
- Pass session tags in AWS STS
- Monitor and control actions taken with assumed roles (source identity)
- The confused deputy problem
- Credential and profile resolution — AWS SDK for .NET v4
- Multi-factor authentication for AWS account root user
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.
Least privilege in practice with IAM Access Analyzer
Run a repeatable least-privilege workflow: start narrow, use condition keys and ABAC, generate policies from CloudTrail activity, remove unused access, and gate every policy change with IAM Access Analyzer checks from C#.
Permission boundaries, SCPs, RCPs and resource-based policies
Delegate IAM safely with permission boundaries, set organisation-wide guardrails with SCPs and RCPs, and use resource-based policies to build a data perimeter and controlled cross-account access.