Join our Newsletter — 33% off our NHI Course
Home› Guides› How to fix AWS ExpiredToken and InvalidClientTokenId errors…
Guide Cloud & Workload Identity

How to fix AWS ExpiredToken and InvalidClientTokenId errors in scripts and pipelines: find the credential, then fix its lifetime

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 13 min read
On this page

Most AWS ExpiredToken and InvalidClientTokenId errors in scripts and pipelines are not permission problems: they mean the code picked up a different credential than you thought, or a temporary credential outlived its session. This guide shows how to find which credential a failing job is really using, how session duration and role chaining limits work, and how to fix the error without falling back to long lived access keys.

It is written for platform engineers, DevOps teams and identity teams who own the roles, sessions and pipeline identities that call AWS. If your error is AccessDenied rather than a token error, see our AWS AccessDenied Troubleshooting Guide instead. For background on how roles and sessions are issued, see our AWS STS and AssumeRole Guide.

This is an independent guide from NHI Mgmt Group, based on AWS's public documentation as of November 2026. It is not sponsored or reviewed by AWS. Product features change, so confirm settings against AWS's current documentation.

Key takeaways

  • An expired token error means the caller sent a temporary credential whose session has ended. The fix is to get a new one automatically, not to make sessions as long as possible.
  • An invalid token error usually means the access key ID or session token is not one AWS recognises in that context: a leftover environment variable, a key that was deleted, a mismatched key and token pair, or a token used in a Region that does not accept it.
  • AWS SDKs and the CLI search a credential chain and stop at the first valid source. Environment variables override profiles, so a stale AWS_SESSION_TOKEN beats a perfectly good role.
  • AssumeRole sessions default to one hour, can run from 15 minutes up to the role's maximum session duration (at most 12 hours), and are capped at one hour when roles are chained.
  • Tokens from the global STS endpoint are only valid in Regions enabled by default unless you change the account setting. Use Regional STS endpoints.
  • Never fix a token error by pasting a long lived IAM user key into the pipeline. That trades a visible failure for a hidden risk.

What each error is telling you

The AWS STS common errors reference describes ExpiredTokenException as "The security token included in the request has expired. Request a new security token and try again", returned with HTTP status 403. Services other than STS return the same idea under the code ExpiredToken. In practice the message appears when a role session, federated session or GetSessionToken session reaches its expiry time while a script is still running, or when a script loads saved temporary credentials that expired earlier.

AssumeRoleWithWebIdentity and related calls return ExpiredToken for a different reason. The AssumeRole family API reference describes it as "The web identity token that was passed is expired or is not valid. Get a new identity token from the identity provider and then retry the request." In a pipeline that means the OIDC token issued by your CI system was too old by the time it reached STS, not that an AWS session expired.

InvalidClientTokenId means AWS could not match the access key ID or token to valid credentials in the context of the request. The STS common errors page documents the closely related UnrecognizedClientException as meaning the access key ID "doesn't exist in our records". Typical causes are:

  • An access key that has been deleted or deactivated, often by rotation or by an incident response team.
  • A temporary access key ID sent without its session token, or with a token from a different session.
  • A session token issued by the global STS endpoint being used in a Region that was enabled manually.
  • Credentials for one partition, such as AWS GovCloud (US) or the China Regions, used against another.

Two other errors are often confused with these. RequestExpired is returned, according to the same page, when the request took more than 15 minutes to reach the service, the date stamp is more than 15 minutes in the future, or a pre-signed URL has expired. That usually points to clock drift on the host or to a stale pre-signed URL. MissingAuthenticationToken means no credentials were found or sent at all.

Step one: find the credential the job really uses

The AWS SDKs and Tools reference guide explains that the SDKs search a chain of providers and that "After valid credentials are found, the search is stopped." It also says that settings specified in code always take precedence, followed by environment variables and then the shared config and credentials files. Providers in the chain commonly include:

  1. Access keys in environment variables such as AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
  2. Web identity or OIDC federation, which assumes a role using a JSON Web Token.
  3. A login session from the console.
  4. IAM Identity Center.
  5. A role assumed from a profile.
  6. Container credentials for Amazon ECS and Amazon EKS.
  7. A credential process, including IAM Roles Anywhere.
  8. Amazon EC2 instance profile credentials from the instance metadata service.

The exact order varies by SDK, so check your language's documentation. The main point holds across all of them: an earlier source wins even if it holds an expired or deleted credential. A runner that still has AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN exported from a previous step will never reach the instance role or the web identity provider configured further down.

For the CLI, the configuration files reference states that profile values are used "unless they are overridden by the presence of an environment variable with the same name, or a command line option with the same name". It also says that if a profile with the same name has credentials in both the credentials and config files, the credentials file wins, and that aws_session_token can be overridden by AWS_SESSION_TOKEN.

A short diagnostic routine that works in almost any pipeline:

  1. Run aws configure list. The LOCATION column shows whether each value came from an environment variable, a shared file or another source.
  2. Run aws sts get-caller-identity in the same step that fails. If it also fails, the problem is the credential, not the service you are calling.
  3. Print which AWS environment variables are set, without printing their values. Look for AWS_PROFILE, AWS_ACCESS_KEY_ID, AWS_SESSION_TOKEN, AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE.
  4. Check whether an earlier step wrote temporary credentials to a file or to the environment, and when.
  5. Note the Region and the STS endpoint the client uses.

Do not log secret values while you debug. Mask them, and treat any credential that has appeared in logs as exposed.

Step two: understand session duration

The AssumeRole API reference sets out the rules. DurationSeconds "can range from 900 seconds (15 minutes) up to the maximum session duration set for the role", and "By default, the value is set to 3600 seconds." If you ask for more than the role allows, the call fails. The IAM documentation on role settings adds that the maximum session duration "can have a value from 1 hour to 12 hours", with a default maximum of 1 hour, and that a change "doesn't take effect until the next time someone assumes this role."

SituationSession limit from AWS documentation
AssumeRole with no duration requested3,600 seconds (1 hour)
AssumeRole with a duration requested900 seconds up to the role's maximum session duration
Role maximum session duration1 to 12 hours, default 1 hour
Role chaining (a role session assuming another role)Maximum of one hour; requests above 3,600 seconds fail

Role chaining causes many pipeline surprises. The AssumeRole reference states that "Role chaining limits your AWS CLI or AWS API role session to a maximum of one hour." A job that uses its runner role to assume a deployment role, and then a second role in a target account, gets at most an hour on the final session, whatever the target role's maximum is set to. A long database migration or a Terraform apply across many accounts can run past that.

The right response depends on why the job runs long:

  • If the SDK can refresh credentials, let it. The SDKs and Tools reference states that with the standard providers, the SDKs "always attempt to renew credentials automatically when they expire", with no extra code needed.
  • If the script captured credentials once and exported them, it has opted out of refresh. Change it to use a profile with role_arn and source_profile or credential_source, or a web identity token file, so the SDK can assume the role again.
  • If the job is chained, remove a hop. Grant the runner identity permission to assume the final role directly, with a trust policy scoped to that runner.
  • If the job truly needs a long single session, raise the role's maximum session duration a step at a time and record why. NHI Mgmt Group recommends keeping the shortest duration that works and reviewing extended roles quarterly.

Step three: check Region and endpoint

The IAM documentation on STS Regions states that "Session tokens from Regional AWS STS endpoints are valid in all AWS Regions. Session tokens from the global STS endpoint are valid only in AWS Regions that are enabled by default." It explains that version 1 tokens from the global endpoint do not work in manually enabled Regions such as Asia Pacific (Hong Kong), while version 2 tokens work in all Regions but are longer, which can break systems that store tokens in fixed size fields.

If a job works in one Region and fails with an invalid token in an opt-in Region, check:

  • Whether the client calls the global endpoint, sts.amazonaws.com. Configure the SDK to use Regional STS endpoints.
  • Whether the account setting for session tokens from the global endpoint is set to all Regions. It is changed with aws iam set-security-token-service-preferences and needs the iam:SetSecurityTokenServicePreferences permission.
  • Whether the target account has the Region enabled. For cross account AssumeRole in an opt-in Region, the documentation says the target account must have that Region enabled.
  • Whether STS is active in that Region. AssumeRole returns RegionDisabled when STS is not activated in the requested Region for the account generating credentials.

Step four: fix the pipeline pattern

Once you know the cause, fix the pattern rather than the single run. Common pipeline fixes:

  • Clear inherited credentials. Unset AWS credential variables at the start of each job, or run each job in a clean environment, so the chain reaches the intended provider.
  • Request the web identity token late. Fetch the CI OIDC token just before calling AssumeRoleWithWebIdentity, not at the start of a long job, and let the SDK read it from a token file so it can refresh.
  • Split long jobs. Break a multi hour task into stages that each assume the role afresh.
  • Pin the profile. Set AWS_PROFILE explicitly in jobs that use named profiles, and avoid a [default] profile with static keys on shared runners.
  • Use instance or container roles on self hosted runners. The SDK refreshes these automatically from the metadata service or container endpoint. Our EC2 Instance Metadata Service Hardening Guide covers protecting that path.
  • Fix clocks. If you see RequestExpired, make sure the host keeps accurate time.

For workloads outside AWS, such as on premises servers, IAM Roles Anywhere issues temporary credentials through a credential process using X.509 certificates; see our AWS IAM Roles Anywhere Security Guide.

Why the quick fix is the wrong fix

The fastest way to make a token error disappear is to create an IAM user, generate an access key and store it as a pipeline secret. Access keys for IAM users do not expire on their own, so the error goes away. So does most of your control. A static key can be copied from logs, caches and forks, used from anywhere, and is easy to forget during rotation.

From an NHI point of view, a token error is a useful signal: it shows that short lived credentials are doing their job. Treat each error as a prompt to make refresh work properly. If you find long lived keys in pipelines while you investigate, plan their removal; our How to audit AWS IAM Roles Anywhere and OIDC identity providers guide covers reviewing the federation trust you will rely on instead.

When an expired or invalid token is a security event

Not every token error is a bug. Raise it with your security team when:

  • An InvalidClientTokenId burst appears for an access key that was recently deactivated after a suspected leak. Someone may still be trying to use it.
  • Errors come from source IP addresses, user agents or Regions your pipelines never use.
  • A role's sessions have been revoked by an incident responder. The IAM role settings page points to revoking role temporary security credentials as the way to end existing sessions, and failures that follow are expected.
  • Someone raises a role's maximum session duration or requests a long lived key without a ticket.

Failed calls are recorded in CloudTrail with an error code, so build a simple view of token errors by identity and source. A sudden change in that view is worth a look.

Common failure patterns

  • Stale environment variables: an earlier step or a runner image exports expired session credentials that mask the intended role.
  • Exported credentials with no refresh: a script calls assume-role once, exports the result, then runs longer than the session.
  • Hidden role chaining: a job hops through two roles and hits the one hour cap even though the final role allows 12 hours.
  • Duration requested above the role maximum: the AssumeRole call itself fails because DurationSeconds exceeds the role's setting.
  • Global endpoint tokens in opt-in Regions: version 1 tokens rejected outside default Regions.
  • Missing session token: a temporary key ID sent without AWS_SESSION_TOKEN.
  • Static key as the fix: the error is "solved" with a long lived IAM user key stored in CI.

Practitioner checklist

  • Run aws configure list and aws sts get-caller-identity in the failing step before changing anything.
  • Clear inherited AWS credential variables at the start of every pipeline job.
  • Let the SDK assume roles and refresh credentials; avoid exporting one time credentials into long jobs.
  • Map role chains and remove hops for jobs that need more than an hour.
  • Keep DurationSeconds within the role's maximum session duration and record any increase.
  • Configure SDKs to use Regional STS endpoints, and check token version settings if you use opt-in Regions.
  • Do not replace temporary credentials with IAM user access keys; remove any you find.
  • Alert on bursts of token errors for deactivated keys and from unusual sources.

Standards and references

Related NHI Mgmt Group resources: AWS AccessDenied Troubleshooting Guide · AWS STS and AssumeRole Guide · AWS IAM Roles Anywhere Security Guide · EC2 Instance Metadata Service Hardening Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.