Data

AWS Credentials: Authentication, Access Keys, Roles, and Secure Configuration

Learn how AWS credentials authenticate requests, how IAM users and roles work, how CLI and SDK providers select credentials, and how to manage credentials securely.

AWS credentials are authentication material or identity context used to sign in to AWS or sign AWS API requests. The credential source might be an AWS account root user, IAM user, federated identity, IAM role, or a workload identity.

Authentication verifies who or what is making a request. Authorization determines whether that authenticated principal is allowed to perform the requested action on the requested resource. A request can authenticate successfully and still receive AccessDenied because its policies do not permit the action.

In AWS, a principal is an identity that can make a request. Examples include an IAM user, IAM role, AWS account, or federated identity.

What AWS Credentials Do

When the AWS CLI, an SDK, or an application calls an AWS service, AWS must determine the caller's identity. Programmatic requests are commonly signed with an access key ID and secret access key. Requests made with temporary credentials also include a session token.

After identifying the principal, AWS evaluates permission policies. These can include identity policies, resource policies, permissions boundaries, session policies, and AWS Organizations service control policies. Explicit denies can block an action even when an allow exists.

Credentials are associated with different identity types:

  • The root user represents the AWS account itself.
  • An IAM user is a long-term identity intended for a person or legacy application pattern.
  • A federated identity is supplied by an external identity provider or IAM Identity Center.
  • An IAM role is an assumable identity used by people, applications, AWS services, and other accounts.

AWS Credential Types

Credential typePrimary useTypical lifetimeHow it is obtainedRecommended useKey security considerations
Root user sign-in credentialsAccount-level tasks that cannot be performed otherwisePersistent until changedAWS account sign-inEmergency or account-management tasks onlyEnable MFA; do not create root access keys; do not use for daily work
IAM user console passwordHuman console sign-inPersistent until changed or disabledIAM administrator or approved identity processLegacy or specific IAM-user workflowsUse MFA and least privilege; prefer workforce federation where available
IAM user access keysCLI, SDK, and application requestsLong-term until rotated or deactivatedCreated for an IAM userOnly when temporary or role-based access is not practicalThe secret is shown only at creation; protect and rotate it
Temporary security credentialsShort-lived API accessLimited session durationAWS STS, IAM Identity Center, federation, or a workload roleApplications, automation, and human sessionsUse the session token; refresh before expiration
IAM role credentialsWorkloads, federation, and cross-account accessShort-lived and automatically replaceable by supported providersA role is assumed directly or through an AWS servicePreferred pattern for most workloadsSecure the trust policy and keep permissions narrow
Federated or single sign-on credentialsHuman access across accounts and rolesSession-basedExternal identity provider or IAM Identity CenterWorkforce accessProtect the identity-provider account and require MFA
MFA device and codeAdditional authentication factorCodes are short-livedHardware or software MFA deviceRoot, privileged, and sign-in protectionMFA supplements credentials; it is not an access key pair

Access Keys

An access key is a pair:

  • Access key ID: the non-secret identifier.
  • Secret access key: confidential key material used to sign requests.

Access keys are primarily used by the AWS CLI, AWS SDKs, infrastructure tools, and applications. The secret access key is displayed only when the key is created. If it is lost, create a replacement rather than expecting AWS to display it again.

An access key does not define what the caller may do. IAM policies define permissions. The key identifies or authenticates the principal associated with it; policy evaluation determines authorization.

Long-Term and Temporary Credentials

CharacteristicIAM user access keysTemporary role credentials
LifetimeLong-term until rotated, deactivated, or deletedExpires after a role or identity session
Credential setAccess key ID and secret access keyAccess key ID, secret access key, and session token
Typical sourceIAM user credential creationAWS STS, federation, IAM Identity Center, or an attached workload role
Operational riskCan remain usable after being copied or forgottenExposure window is limited, but the session must be refreshed
Preferred useOnly for constrained cases where roles are unavailableMost workloads, automation, federation, and cross-account access

AWS Security Token Service, or STS, issues temporary credentials. The session token is required in addition to the access key ID and secret access key. Temporary credentials have an expiration time, so applications must obtain a new set before the current one expires.

Supported SDK credential providers refresh temporary credentials automatically. This depends on the provider and configuration. An application that manually copies temporary values may not refresh them, so prefer the SDK's default credential provider chain or an official refresh-capable provider.

IAM Roles and Assumed Roles

An IAM role is an identity with permission policies and a trust relationship, but it has no permanent login credentials of its own. A principal obtains a role session by assuming the role, commonly through STS.

A role has two important policy areas:

  • Trust policy: determines which principals may assume the role. For example, it can trust an EC2 service, a specific AWS account, a federated identity, or a named principal.
  • Permission policy: determines what the role session can do after assumption, such as reading specific objects in an S3 bucket.

Assuming a role creates a role session, which is a temporary identity context with a temporary access key ID, secret access key, session token, and expiration time.

Common Role Uses

  • EC2: an instance profile makes role credentials available to the application through the instance metadata credential provider.
  • Lambda: the function execution role supplies permissions to the function runtime.
  • ECS: an ECS task role supplies credentials to containers in a task.
  • EKS: workload identity can associate Kubernetes workloads with IAM roles.
  • Cross-account access: a principal in one account assumes a role trusted by another account.
  • Human federation: a workforce identity assumes roles in one or more AWS accounts.

Roles are generally preferred for workloads because credentials are short-lived and can be delivered by the runtime instead of being saved on a server.

Credential Provider Chains and Resolution

A credential provider chain is the ordered collection of locations and mechanisms that an AWS CLI or SDK checks for credentials. Common sources include:

  • Environment variables.
  • A selected named profile.
  • Shared credentials and AWS config files.
  • IAM Identity Center or another federated session.
  • Web identity tokens, commonly used by federated workloads.
  • ECS task metadata credentials.
  • EC2 instance metadata credentials.
  • Other provider mechanisms configured by a specific SDK or tool.
Credential sourceTypical location or mechanismBest use caseCommon risk or troubleshooting concern
Environment variablesShell or process environmentShort-lived local tasks and CI jobs with controlled secret injectionMay override an intended profile and appear in logs or process tooling
Named profileShared credentials or AWS config fileSeparating development, staging, production, and role sessionsWrong profile or stale cached session
IAM Identity Center sessionLocal login and cached session dataHuman workforce accessSession expiration or failed reauthentication
Web identity tokenToken file plus role configurationFederated workloads such as Kubernetes applicationsMissing token, wrong role trust, or expired token
ECS task metadataContainer task role endpointContainers running on ECSIncorrect task role or unavailable metadata endpoint
EC2 instance metadataInstance profile and metadata endpointApplications on EC2No attached role, blocked metadata access, or incorrect role

Exact precedence varies by SDK, CLI, and tool version. Do not assume that a profile wins over environment variables or that every SDK implements providers in the same order. An unexpected source can cause commands to run in the wrong account or under the wrong role.

Use STS to identify the active caller:

aws sts get-caller-identity

The response includes an account ID and an ARN. The ARN can identify an IAM user or an assumed role. Repeat the check with a named profile:

aws sts get-caller-identity --profile development

AWS CLI Profiles

An AWS profile is a named local configuration set. Profiles help separate personal, development, staging, production, and cross-account access. Use explicit profiles for sensitive operations rather than relying on an implicit shell state.

The AWS CLI commonly uses two local files:

  • Shared credentials file: commonly stores access key values for profiles.
  • AWS config file: commonly stores regions, output settings, role profiles, and other CLI configuration.

Configure a profile interactively with:

aws configure --profile development

Use an approved IAM Identity Center or role-based authentication flow instead of entering long-lived keys when that option is available. Treat both files as sensitive and never commit them.

A placeholder-only credentials file might look like this:

[development]
aws_access_key_id = EXAMPLEACCESSKEYID
aws_secret_access_key = EXAMPLESECRETKEY

[production]
aws_access_key_id = EXAMPLEACCESSKEYID
aws_secret_access_key = EXAMPLESECRETKEY

Select a profile for one command with --profile, or for a shell session with:

export AWS_PROFILE=development
aws sts get-caller-identity --profile development

Unset or change AWS_PROFILE when switching contexts. A role profile can use a source profile to obtain temporary credentials in another account:

[profile audit-account]
role_arn = arn:aws:iam::123456789012:role/AuditReadOnly
source_profile = development
role_session_name = local-audit-session
region = us-east-1

The source identity must be allowed to call sts:AssumeRole, and the target role's trust policy must trust that source. Verify the result:

aws sts get-caller-identity --profile audit-account

Environment Variables and Application Configuration

Common AWS-related environment variables include:

  • AWS_ACCESS_KEY_ID: access key ID.
  • AWS_SECRET_ACCESS_KEY: secret access key.
  • AWS_SESSION_TOKEN: required with temporary credentials.
  • AWS_PROFILE: named profile selected by the process.
  • AWS_REGION: preferred AWS Region setting for many SDKs and tools.
  • AWS_DEFAULT_REGION: default Region setting used by the CLI and some integrations.

Environment variables can be appropriate for a short-lived local command or a CI job that injects secrets through a protected mechanism. They can also be exposed through shell history, debugging output, process listings, build logs, crash reports, or child processes. Never print them for diagnostics.

For applications, prefer an attached workload role, web identity, federation, or a managed secret store such as an approved Secrets Manager or Parameter Store design. Do not embed values in source code, container images, configuration committed to a repository, or infrastructure templates.

Secure Credential Practices

  • Do not use root access keys for daily work or applications. Root access keys should not be created.
  • Enable MFA for the root user and privileged identities.
  • Apply least privilege: grant only the actions and resources required for a task.
  • Use permissions boundaries where appropriate to limit the maximum permissions an identity can receive.
  • Prefer IAM roles and temporary credentials over long-lived IAM user access keys.
  • Use separate identities, roles, and preferably accounts for people and environments.
  • Rotate, deactivate, and delete unused access keys.
  • Store secrets in approved secret-management systems rather than repositories or plaintext files.
  • Use CloudTrail, credential reports, access-key metadata, Access Analyzer, and alerting to monitor access.
  • Use secret scanning in repositories and CI/CD pipelines.

Credential Lifecycle Management

  1. Create only when necessary: choose federation or a role before creating a long-lived key.
  2. Distribute safely: deliver secrets through an approved secret-management or identity system. Never send them through chat or email.
  3. Validate access: run aws sts get-caller-identity and test only the required action.
  4. Monitor use: review CloudTrail activity, key age, and last-used information.
  5. Rotate without interruption: create a second key if account limits allow, update the application secret source, validate the new key, then deactivate the old key.
  6. Deactivate obsolete keys: monitor for failures after deactivation.
  7. Delete retired keys: remove them after confirming no dependent process still uses them.

Useful IAM inspection commands include:

aws iam list-access-keys --user-name example-user
aws iam get-access-key-last-used --access-key-id AKIAEXAMPLEKEYID

Use these commands only when authorized to inspect IAM data, and never expose the secret paired with an access key ID.

Responding to a Compromised Credential

Credentials are commonly exposed through source repositories, public artifacts, logs, chat messages, copied configuration, container images, and accidental sharing. Treat any exposed secret as compromised even if it appears unused.

PhaseActionPurposeEvidence or validation
ContainDeactivate the exposed access key immediately, or replace the affected role/session sourceStop further useKey status is inactive or the source role has been changed
InvestigateReview CloudTrail and service activityFind unauthorized calls and affected resourcesEvent records, caller ARN, timestamps, regions, and requested actions
RecoverIssue replacement credentials through an approved mechanism and update workloadsRestore legitimate service without reusing the exposed valueCaller identity and application health checks succeed
Remove exposureRemove the value from repositories, logs, artifacts, and deployment configurationPrevent continued disclosureRepository history and artifact locations are reviewed; exposed copies are invalidated
PreventAdd secret scanning, managed secret storage, role-based access, and organization guardrailsReduce recurrenceScanning and alerting tests detect new accidental secrets

After containment, investigate affected policies, roles, resources, and accounts. Review unexpected API activity in CloudTrail, including changes to IAM, networking, storage, compute, and billing-related resources. If an incident is significant, follow the organization's security incident process and preserve evidence.

Verification and Auditing

  • STS caller identity: confirms the account, principal, or assumed role currently used by a CLI or application.
  • IAM access-key metadata: shows key status and last-used information for authorized administrators.
  • CloudTrail: records API activity and helps connect actions to credentials, roles, accounts, regions, and times.
  • IAM credential reports: provide account-level information about credential status, age, and use for IAM users.
  • IAM Access Analyzer: helps identify unintended external access and supports policy analysis.

Successful authentication proves only that AWS recognized the caller. Authorization still depends on policy evaluation, resource conditions, session restrictions, boundaries, and organization controls.

Troubleshooting Credential Problems

Unable to Locate Credentials

Likely causes include no configured profile or environment variables, an incorrect profile, an expired temporary session, or an unavailable metadata or web-identity provider. Check the selected profile, authenticate again, run the caller-identity command, and verify that a workload role is attached and reachable when applicable.

The Command Uses the Wrong Account

Check for an unexpected AWS_PROFILE, environment variables that override the intended profile, or a higher-precedence provider. Run:

aws sts get-caller-identity
aws sts get-caller-identity --profile development

Inspect active AWS-related environment variables, specify the intended profile explicitly, and review the provider order for the tool or SDK version in use.

AccessDenied

First confirm the caller ARN. Then review identity policies, resource policies, permissions boundaries, session policies, service control policies, requested action, resource ARN, Region, and policy conditions. Also verify that the application did not assume an unexpected role.

A Role Cannot Be Assumed

Inspect the role trust policy and the calling principal's permission to use sts:AssumeRole. Check required external IDs, MFA conditions, session tags, organization conditions, and the target role ARN.

Temporary Credentials Expired

Obtain a new authenticated session and check the role-session expiration. For workloads, verify runtime role configuration, metadata or token endpoint connectivity, refresh support, and stale credential caches.

An Access Key Appeared in a Repository or Log

Deactivate it immediately, replace the workload credential, review CloudTrail, remove the secret from the exposure location, invalidate copied artifacts, and add secret scanning. Removing text alone is not enough: the credential must be disabled or replaced.

Practical Workflows

Confirm the AWS CLI Identity

  1. Run aws sts get-caller-identity.
  2. Read the returned account ID and ARN.
  3. Repeat with --profile when testing a named profile.
  4. Before a production change, verify the account and role again immediately before the command.

Separate Development and Production Profiles

Create separate named profiles with distinct permissions and Regions. Use an explicit profile for sensitive commands:

aws sts get-caller-identity --profile development
aws sts get-caller-identity --profile production

Use separate accounts and identities where practical. This reduces the chance that a development shell can modify production resources.

Give an EC2 Application Access to S3

  1. Create an IAM role trusted by the EC2 service.
  2. Attach an instance profile containing that role.
  3. Grant only the required S3 actions and resource ARNs.
  4. Launch or associate the instance profile with the instance.
  5. Configure the SDK to use its default provider chain rather than reading a key from a file.
  6. Confirm the application receives rotating role credentials and can perform only the intended S3 operations.

Rotate an IAM User Access Key

  1. Create a second active key if the account's key limit permits it.
  2. Place the new secret in the approved secret source.
  3. Restart or reload the dependent application and validate its caller identity and required operation.
  4. Deactivate the old key.
  5. Monitor for failures and identify any remaining dependency.
  6. Delete the old key after the transition is complete.

Exam-Relevant Notes

  • Authentication and authorization are different: credentials establish identity, while policies determine permissions.
  • An access key ID and secret access key are a pair; temporary credentials add a session token.
  • The secret access key is shown only at creation and must be protected.
  • IAM roles have trust policies for who may assume them and permission policies for what the resulting session may do.
  • Roles and temporary credentials are preferred for workloads and cross-account access.
  • Provider precedence varies by tool and version; use STS caller identity to confirm the active principal.
  • MFA is an additional factor, not a replacement for authorization policies.
  • An authenticated request can still fail with AccessDenied.

For related study, see AWS credentials.