Web identity token credential providers handle OAuth 2.0 and OpenID Connect tokens for web identity federation, supporting integration with external identity providers and Kubernetes service accounts.
Creates credentials from OAuth 2.0 access tokens or OpenID Connect ID tokens.
/**
* Creates a credential provider function that gets credentials calling STS AssumeRoleWithWebIdentity API
* @param init - Web token configuration parameters
* @returns Web identity credential provider function
*/
function fromWebToken(init: FromWebTokenInit): AwsCredentialIdentityProvider;
interface FromWebTokenInit {
/** ARN of the role that the caller is assuming (required) */
roleArn: string;
/** The OAuth 2.0 access token or OpenID Connect ID token provided by identity provider (required) */
webIdentityToken: string;
/** Optional identifier for the assumed role session */
roleSessionName?: string;
/** Optional fully qualified host component of the domain name of the identity provider */
providerId?: string;
/** Optional ARNs of IAM managed policies to use as managed session policies */
policyArns?: PolicyDescriptorType[];
/** Optional IAM policy in JSON format to use as inline session policy */
policy?: string;
/** Optional duration in seconds of the role session (default 3600) */
durationSeconds?: number;
/** Optional custom STS client configurations */
clientConfig?: STSClientConfig;
/** Optional custom STS client middleware plugins */
clientPlugins?: Pluggable<any, any>[];
/** Optional function for custom role assumption with web identity */
roleAssumerWithWebIdentity?: (params: AssumeRoleWithWebIdentityCommandInput) => Promise<AssumeRoleWithWebIdentityCommandOutput>;
}Creates credentials by reading OIDC tokens from files, commonly used with Kubernetes service accounts.
/**
* Creates a credential provider function that reads OIDC token from file and calls STS AssumeRoleWithWebIdentity API
* @param init - Token file configuration parameters
* @returns Web identity credential provider function
*/
function fromTokenFile(init?: FromTokenFileInit): AwsCredentialIdentityProvider;
interface FromTokenFileInit {
/** Optional path to web identity token file (reads from AWS_WEB_IDENTITY_TOKEN_FILE if not provided) */
webIdentityTokenFile?: string;
/** Optional ARN of role to assume (reads from AWS_ROLE_ARN if not provided) */
roleArn?: string;
/** Optional role session name (reads from AWS_ROLE_SESSION_NAME if not provided) */
roleSessionName?: string;
/** Optional custom STS client configurations */
clientConfig?: STSClientConfig;
/** Optional custom STS client middleware plugins */
clientPlugins?: Pluggable<any, any>[];
}Usage Examples:
import { S3Client } from "@aws-sdk/client-s3";
import { fromWebToken, fromTokenFile } from "@aws-sdk/credential-providers";
// Direct web token usage
const client = new S3Client({
region: "us-east-1",
credentials: fromWebToken({
roleArn: "arn:aws:iam::123456789012:role/WebIdentityRole",
webIdentityToken: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", // JWT token
roleSessionName: "WebIdentitySession"
})
});
// Token from file (Kubernetes/EKS pattern)
const k8sClient = new S3Client({
region: "us-east-1",
credentials: fromTokenFile({
webIdentityTokenFile: "/var/run/secrets/eks.amazonaws.com/serviceaccount/token",
roleArn: "arn:aws:iam::123456789012:role/EKSServiceAccountRole",
roleSessionName: "EKSPodSession"
})
});
// Using environment variables (standard EKS/Fargate setup)
const envClient = new S3Client({
region: "us-east-1",
credentials: fromTokenFile() // Reads from AWS_WEB_IDENTITY_TOKEN_FILE and AWS_ROLE_ARN
});import { fromWebToken } from "@aws-sdk/credential-providers";
async function getGoogleCredentials(googleToken: string) {
return new S3Client({
region: "us-east-1",
credentials: fromWebToken({
roleArn: "arn:aws:iam::123456789012:role/GoogleFederatedRole",
webIdentityToken: googleToken,
providerId: "accounts.google.com",
roleSessionName: "GoogleUserSession"
})
});
}import { fromWebToken } from "@aws-sdk/credential-providers";
async function getFacebookCredentials(fbToken: string) {
return new S3Client({
region: "us-east-1",
credentials: fromWebToken({
roleArn: "arn:aws:iam::123456789012:role/FacebookFederatedRole",
webIdentityToken: fbToken,
providerId: "graph.facebook.com",
roleSessionName: "FacebookUserSession"
})
});
}import { fromWebToken } from "@aws-sdk/credential-providers";
async function getOIDCCredentials(oidcToken: string) {
return new S3Client({
region: "us-east-1",
credentials: fromWebToken({
roleArn: "arn:aws:iam::123456789012:role/CustomOIDCRole",
webIdentityToken: oidcToken,
providerId: "auth.example.com",
roleSessionName: "CustomOIDCSession",
durationSeconds: 7200 // 2 hours
})
});
}# Kubernetes Service Account with IAM Role annotation
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-service-account
namespace: default
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/EKSServiceAccountRole// Application code running in EKS pod
import { S3Client } from "@aws-sdk/client-s3";
import { fromTokenFile } from "@aws-sdk/credential-providers";
// Automatically uses service account token
const client = new S3Client({
region: process.env.AWS_REGION,
credentials: fromTokenFile()
});import { fromTokenFile } from "@aws-sdk/credential-providers";
// Fargate automatically provides these environment variables
const client = new S3Client({
region: "us-east-1",
credentials: fromTokenFile({
// These are set automatically by Fargate
webIdentityTokenFile: process.env.AWS_WEB_IDENTITY_TOKEN_FILE,
roleArn: process.env.AWS_ROLE_ARN,
roleSessionName: process.env.AWS_ROLE_SESSION_NAME
})
});Apply additional restrictions during role assumption:
import { fromWebToken } from "@aws-sdk/credential-providers";
const restrictedClient = new S3Client({
region: "us-east-1",
credentials: fromWebToken({
roleArn: "arn:aws:iam::123456789012:role/WebIdentityRole",
webIdentityToken: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
// Inline session policy
policy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Action: ["s3:GetObject"],
Resource: "arn:aws:s3:::user-bucket/*"
}
]
}),
// Managed session policies
policyArns: [
{ arn: "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" }
],
roleSessionName: "RestrictedWebSession"
})
});The fromTokenFile provider reads these environment variables:
Web identity tokens typically have expiration times:
import { fromWebToken } from "@aws-sdk/credential-providers";
// Tokens should be refreshed before expiration
async function createCredentialsWithRefresh(getToken: () => Promise<string>) {
const token = await getToken();
return fromWebToken({
roleArn: "arn:aws:iam::123456789012:role/WebIdentityRole",
webIdentityToken: token,
durationSeconds: 3600, // Match or be less than token expiration
roleSessionName: "RefreshableSession"
});
}Common errors and handling strategies:
import { fromWebToken } from "@aws-sdk/credential-providers";
try {
const credentials = await fromWebToken({
roleArn: "arn:aws:iam::123456789012:role/WebIdentityRole",
webIdentityToken: "invalid-token"
})();
} catch (error) {
if (error.name === "InvalidIdentityToken") {
console.error("Web identity token is malformed or expired");
} else if (error.name === "IDPRejectedClaim") {
console.error("Identity provider rejected the token claims");
} else if (error.name === "IDPCommunicationError") {
console.error("Cannot communicate with identity provider");
} else if (error.name === "AccessDenied") {
console.error("Not authorized to assume the specified role");
} else {
console.error("Failed to assume role with web identity:", error.message);
}
}IAM roles used with web identity must have appropriate trust policies:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789012:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B716D3041E"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B716D3041E:sub": "system:serviceaccount:default:my-service-account"
}
}
}
]
}fromWebToken and fromTokenFile)fromWebToken only, fromTokenFile not available)fromWebToken only)