Why AWS returns ExpiredToken, how to tell a stale environment variable from an expired SSO session or a role session that outlived its duration, and how to make long-running code refresh credentials on its own.

AWS temporary credentials come with an expiry, and once it passes, every call signed with them fails with ExpiredToken: The security token included in the request is expired. The permissions are fine, which is why the error confuses people, and the fix is always about where the credentials came from and why nothing refreshed them.
The causes split by environment, so this guide starts by finding the source.
The SDKs use the first source in the credential provider chain that returns something, and environment variables come first. Check what is set and which identity AWS sees:
An access key starting with ASIA is temporary, and Type env shows it came from the shell rather than your profile. This is the most common laptop case: someone pasted export lines from an assume-role or the SSO portal hours ago, and running unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN lets the CLI fall back to the profile, which refreshes itself.
AssumeRole sessions last one hour by default. A role's MaxSessionDuration can go up to 12 hours, and the AssumeRole API then accepts a longer DurationSeconds. Role chaining, where a session from one assumed role assumes another, is capped at one hour whatever the role allows, which catches CI pipelines that assume a deploy role from an OIDC role. For SSO, the access portal session length is set by the administrator in IAM Identity Center, and when it ends aws sso login is the only fix.
Long-running code should hold a provider, not a set of credentials. In Go, wrap stscreds.NewAssumeRoleProvider in aws.NewCredentialsCache, which renews the session before it expires:
package main
import (
"context"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/sts"
)
func main() {
ctx := context.Background()
// Base credentials: the task role, instance profile or SSO profile.
base, err := config.LoadDefaultConfig(ctx)
if err != nil {
log.Fatal(err)
}
// Assume the reporting role and keep refreshing it. The cache renews the
// session five minutes before expiry instead of letting calls fail.
provider := stscreds.NewAssumeRoleProvider(sts.NewFromConfig(base), os.Getenv("REPORTS_ROLE_ARN"),
func(o *stscreds.AssumeRoleOptions) {
o.RoleSessionName = "reports-exporter"
o.Duration = time.Hour
})
cfg := base.Copy()
cfg.Credentials = aws.NewCredentialsCache(provider, func(o *aws.CredentialsCacheOptions) {
o.ExpiryWindow = 5 * time.Minute
})
client := s3.NewFromConfig(cfg)
out, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String("acme-reports")})
if err != nil {
log.Fatal(err)
}
log.Printf("%d objects", len(out.Contents))
}
In Python, a profile with role_arn and source_profile (or credential_source = EcsContainer on ECS) makes boto3 refresh automatically, while credentials passed as explicit aws_session_token arguments cannot be refreshed. In Node.js, fromTemporaryCredentials from @aws-sdk/credential-providers does the same job as the Go cache. On ECS, EKS, Lambda and EC2, the platform role is already a refreshing provider, so the ExpiredToken error there almost always means code copied credentials out of the SDK once and kept them.
GitHub Actions with OIDC requests a session through aws-actions/configure-aws-credentials, and its role-duration-seconds input defaults to one hour, so a two-hour integration suite fails partway. Raise role-duration-seconds and the role's MaxSessionDuration together, or split the job, and avoid chaining a second role from the OIDC role, since that session cannot exceed one hour.
Encore brings infrastructure from code, so a scheduled export that writes to S3 declares the bucket and the cron job instead of building clients from session credentials. There is no AssumeRole, provider or cache in the job, which is where the hour-long sessions above usually run out.

Run in your terminal to get started locally.
// reports/reports.go
package reports
import (
"context"
"encoding/csv"
"fmt"
"time"
"encore.dev/cron"
"encore.dev/storage/objects"
)
// S3 on AWS, Cloud Storage on GCP, local storage under encore run.
var Exports = objects.NewBucket("report-exports", objects.BucketConfig{})
// Triggered by the Encore platform in deployed environments.
var _ = cron.NewJob("nightly-export", cron.JobConfig{
Title: "Export yesterday's orders",
Schedule: "0 2 * * *",
Endpoint: ExportOrders,
})
//encore:api private
func ExportOrders(ctx context.Context) error {
day := time.Now().UTC().AddDate(0, 0, -1).Format("2006-01-02")
w := Exports.Upload(ctx, fmt.Sprintf("orders/%s.csv", day))
cw := csv.NewWriter(w)
if err := cw.Write([]string{"order_id", "total_cents"}); err != nil {
w.Abort(err)
return err
}
// ...write one row per order, however long the export takes...
cw.Flush()
if err := cw.Error(); err != nil {
w.Abort(err)
return err
}
return w.Close()
}
Cron jobs are managed by the Encore platform and do not run locally or in preview environments, so during development you run the export by calling ExportOrders from a test, and encore test writes the file to a locally served bucket. On deploy to your own AWS account, Encore creates the S3 bucket, the platform triggers the job on schedule, and Encore provisions an IAM role for the service, as the AWS infrastructure docs describe.
Local development needs no AWS profile at all, which also suits coding agents: an agent can add the export, run it against the local bucket and check the output, without anyone pasting session credentials into its terminal where they would expire mid-task or end up in a log.
Best fit: Teams whose jobs and services talk to S3, SQS or databases in their own AWS account and who want that access to come from the deployed service rather than from credentials the code manages.
The request was signed with temporary credentials, an access key plus a session token from STS, SSO or a role, and that session has passed its expiration time. AWS rejects it with the ExpiredToken error code, and the fix is to get fresh credentials, not to change any permissions.
Usually because AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN are still exported in your shell from an earlier session. Environment variables come first in the credential chain, so the SDK keeps using them. Unset them and the SDK falls through to your refreshed profile.
One hour by default. The role's MaxSessionDuration can be raised to 12 hours, and the caller then requests a longer DurationSeconds. Sessions created by role chaining, where one assumed role assumes another, are limited to one hour regardless of the setting.
Use a credential provider that refreshes itself, such as a profile with role_arn in boto3, stscreds with a credentials cache in Go, or fromTemporaryCredentials in Node.js, instead of exporting static session credentials. On AWS compute, the task or instance role is refreshed by the SDK automatically, and Encore apps on AWS use the IAM role Encore provisions for the service.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.