HTTP credential provider makes GET requests to retrieve credentials from HTTP/HTTPS endpoints, supporting both browser and Node.js environments with security restrictions for acceptable URLs.
Creates credentials by making HTTP GET requests to specified URLs.
/**
* Creates a credential provider that makes HTTP GET requests to retrieve credentials
* @param options - HTTP credential provider configuration
* @returns HTTP credential provider function
*/
function fromHttp(options: FromHttpOptions): AwsCredentialIdentityProvider;
interface FromHttpOptions {
/** Node.js: Full URI for container credentials (takes precedence over relative URI) */
awsContainerCredentialsFullUri?: string;
/** Node.js: Relative URI appended to default link local host 169.254.170.2 */
awsContainerCredentialsRelativeUri?: string;
/** Node.js: Authorization token value for request header */
awsContainerAuthorizationToken?: string;
/** Node.js: Path to file containing authorization token */
awsContainerAuthorizationTokenFile?: string;
/** Browser: Full HTTPS URI for credentials (required in browser) */
credentialsFullUri?: string;
/** Browser: Authorization token for request header */
authorizationToken?: string;
/** Maximum number of retry attempts (default: 3) */
maxRetries?: number;
/** Connection timeout in milliseconds (default: 1000) */
timeout?: number;
/** Optional logger instance */
logger?: Logger;
}
interface HttpProviderCredentials {
AccessKeyId: string;
SecretAccessKey: string;
Token: string;
AccountId?: string;
Expiration: string; // RFC3339 format
}Usage Examples:
import { S3Client } from "@aws-sdk/client-s3";
import { fromHttp } from "@aws-sdk/credential-providers";
// Node.js: Full URI
const nodeClient = new S3Client({
region: "us-east-1",
credentials: fromHttp({
awsContainerCredentialsFullUri: "http://169.254.170.2/v2/credentials/12345"
})
});
// Node.js: Relative URI with authorization
const containerClient = new S3Client({
region: "us-east-1",
credentials: fromHttp({
awsContainerCredentialsRelativeUri: "/v2/credentials/12345",
awsContainerAuthorizationToken: "MySecretToken"
})
});
// Browser: HTTPS only
const browserClient = new S3Client({
region: "us-east-1",
credentials: fromHttp({
credentialsFullUri: "https://credentials.example.com/api/v1/credentials",
authorizationToken: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
})
});The provider reads these environment variables when options are not provided:
import { fromHttp } from "@aws-sdk/credential-providers";
// Uses environment variables automatically
const envClient = new S3Client({
region: "us-east-1",
credentials: fromHttp({}) // Empty options use environment variables
});127.0.0.0/8 or [::1/128]169.254.170.2169.254.170.23 or [fd00:ec2::23]// Valid Node.js URLs
const validNodeUrls = [
"https://credentials.example.com/api",
"http://127.0.0.1:8080/credentials",
"http://169.254.170.2/v2/credentials/abc123",
"http://169.254.170.23/credentials"
];
// Valid browser URLs (HTTPS only)
const validBrowserUrls = [
"https://credentials.example.com/api",
"https://auth.myapp.com/aws-credentials"
];The HTTP endpoint must return JSON in this exact format:
{
"AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
"SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"Token": "AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5T...",
"AccountId": "123456789012",
"Expiration": "2023-12-31T23:59:59Z"
}export AWS_CONTAINER_AUTHORIZATION_TOKEN="MySecretToken"echo "MySecretToken" > /var/secrets/aws-token
export AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE="/var/secrets/aws-token"import { fromHttp } from "@aws-sdk/credential-providers";
const tokenFileClient = new S3Client({
credentials: fromHttp({
awsContainerCredentialsRelativeUri: "/v2/credentials",
awsContainerAuthorizationTokenFile: "/var/secrets/aws-token"
})
});HTTP credentials work seamlessly with ECS container metadata:
// ECS automatically sets these environment variables
import { fromHttp } from "@aws-sdk/credential-providers";
const ecsClient = new S3Client({
region: process.env.AWS_REGION,
credentials: fromHttp({}) // Uses ECS environment variables
});Build custom credential endpoints that return AWS credentials:
// Custom credential service implementation (Node.js server)
import express from 'express';
const app = express();
app.get('/credentials', async (req, res) => {
// Validate authorization token
const token = req.headers.authorization;
if (!isValidToken(token)) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Generate or retrieve temporary credentials
const credentials = await generateTemporaryCredentials();
res.json({
AccessKeyId: credentials.accessKeyId,
SecretAccessKey: credentials.secretAccessKey,
Token: credentials.sessionToken,
Expiration: credentials.expiration.toISOString()
});
});
// Client usage
const customClient = new S3Client({
credentials: fromHttp({
awsContainerCredentialsFullUri: "http://localhost:3000/credentials",
awsContainerAuthorizationToken: "MyCustomToken"
})
});Handle HTTP credential provider errors:
import { fromHttp } from "@aws-sdk/credential-providers";
try {
const credentials = await fromHttp({
credentialsFullUri: "https://credentials.example.com/api"
})();
} catch (error) {
if (error.message.includes('URL not accepted')) {
console.error('URL does not meet security requirements');
} else if (error.message.includes('timeout')) {
console.error('HTTP request timed out');
} else if (error.message.includes('401')) {
console.error('Authorization failed - check token');
} else if (error.message.includes('404')) {
console.error('Credentials endpoint not found');
} else {
console.error('HTTP credentials failed:', error.message);
}
}Credential endpoints must include appropriate CORS headers:
// Server-side CORS configuration
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'https://myapp.com');
res.header('Access-Control-Allow-Headers', 'Authorization');
res.header('Access-Control-Allow-Methods', 'GET');
next();
});Update CSP to allow credential endpoint connections:
<meta http-equiv="Content-Security-Policy"
content="connect-src 'self' https://credentials.example.com;">HTTP credentials are not cached by the provider itself:
import { fromHttp } from "@aws-sdk/credential-providers";
// Each call makes a fresh HTTP request
const provider = fromHttp({
credentialsFullUri: "https://credentials.example.com/api"
});
// To add caching, wrap the provider:
function createCachedHttpProvider(options: FromHttpOptions) {
let cachedCredentials: any = null;
let expiration: Date | null = null;
const httpProvider = fromHttp(options);
return async () => {
if (cachedCredentials && expiration && expiration > new Date()) {
return cachedCredentials;
}
cachedCredentials = await httpProvider();
expiration = cachedCredentials.expiration || new Date(Date.now() + 3600000);
return cachedCredentials;
};
}