Package: github.com/aws/aws-sdk-go-v2/credentials/endpointcreds
The endpointcreds package provides credential retrieval from arbitrary HTTP endpoints, supporting both static and refreshable credentials.
import "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds"This provider retrieves AWS credentials from an HTTP endpoint that returns credentials in JSON format. It supports:
{
"AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
"SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
}{
"AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
"SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"Token": "AQoDYXdzEJr...",
"Expiration": "2016-02-25T06:03:31Z"
}Errors are returned with 400 or 500 HTTP status codes:
{
"code": "ErrorCode",
"message": "Helpful error message."
}package main
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials/endpointcreds"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
func main() {
// Create endpoint credentials provider
provider := endpointcreds.New("http://localhost:8080/credentials")
// Wrap with CredentialsCache for automatic refresh
credentials := aws.NewCredentialsCache(provider)
// Use with AWS service clients
cfg := aws.Config{
Region: "us-east-1",
Credentials: credentials,
}
client := s3.NewFromConfig(cfg)
// Use client
}provider := endpointcreds.New(
"http://localhost:8080/credentials",
func(o *endpointcreds.Options) {
o.AuthorizationToken = "my-secret-token"
},
)
credentials := aws.NewCredentialsCache(provider)package main
import (
"os"
"github.com/aws/aws-sdk-go-v2/credentials/endpointcreds"
)
func main() {
// Read token from file each time credentials are retrieved
tokenProvider := endpointcreds.TokenProviderFunc(func() (string, error) {
token, err := os.ReadFile("/path/to/token/file")
if err != nil {
return "", err
}
return string(token), nil
})
provider := endpointcreds.New(
"http://localhost:8080/credentials",
func(o *endpointcreds.Options) {
o.AuthorizationTokenProvider = tokenProvider
},
)
// Use provider
}import (
"net/http"
"time"
)
customClient := &http.Client{
Timeout: 10 * time.Second,
}
provider := endpointcreds.New(
"http://localhost:8080/credentials",
func(o *endpointcreds.Options) {
o.HTTPClient = customClient
},
)const ProviderName = "CredentialsEndpointProvider"Name identifier for the credentials endpoint provider.
func New(endpoint string, optFns ...func(*Options)) *ProviderReturns a credentials Provider for retrieving AWS credentials from an arbitrary endpoint.
Parameters:
endpoint (string): Required. The HTTP(S) endpoint URL to retrieve credentials fromoptFns (...func(*Options)): Functional options for configuring the providerReturns:
*Provider: Initialized endpoint credentials providerExample:
// Basic endpoint
provider := endpointcreds.New("http://localhost:8080/credentials")
// With authorization
provider := endpointcreds.New(
"http://localhost:8080/credentials",
func(o *endpointcreds.Options) {
o.AuthorizationToken = "secret-token"
},
)type Options struct {
Endpoint string
HTTPClient HTTPClient
APIOptions []func(*middleware.Stack) error
Retryer aws.Retryer
AuthorizationToken string
AuthorizationTokenProvider AuthTokenProvider
CredentialSources []aws.CredentialSource
}Configuration options for the Provider.
Fields:
Endpoint (string): Required. Endpoint URL to retrieve credentials fromHTTPClient (HTTPClient): HTTP client for sending requests. Defaults to standard http.ClientAPIOptions ([]func(*middleware.Stack) error): Options to modify credentials operation invocationRetryer (aws.Retryer): Retryer for determining whether failed requests should be retriedAuthorizationToken (string): Optional static authorization token for the Authorization header. Can be set via AWS_CONTAINER_AUTHORIZATION_TOKEN environment variableAuthorizationTokenProvider (AuthTokenProvider): Optional dynamic token provider. Overrides AuthorizationToken if set. Can be configured via AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE environment variableCredentialSources ([]aws.CredentialSource): Credential chain information for reporting (not meant to be set directly)type Provider struct {
// Has unexported fields
}Satisfies the aws.CredentialsProvider interface for retrieving credentials from an arbitrary endpoint.
func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error)Attempts to request credentials from the configured endpoint.
Parameters:
ctx (context.Context): Context for the request, supports cancellation and timeoutsReturns:
aws.Credentials: Retrieved credentials (static or with expiration)error: Error if retrieval failsExample:
creds, err := provider.Retrieve(context.TODO())
if err != nil {
log.Fatalf("Failed to retrieve credentials: %v", err)
}
if creds.CanExpire {
fmt.Printf("Credentials expire at: %s\n", creds.Expires)
}func (p *Provider) ProviderSources() []aws.CredentialSourceReturns the credential chain that was used to construct this provider.
Returns:
[]aws.CredentialSource: Credential source chain for debuggingtype HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}Interface for sending HTTP requests. Allows custom HTTP client implementations.
Methods:
Do(*http.Request) (*http.Response, error): Executes an HTTP requesttype AuthTokenProvider interface {
GetToken() (string, error)
}Interface for dynamically loading authorization tokens. The token value is used as the Authorization header in credential requests.
Methods:
GetToken() (string, error): Retrieves the current authorization tokentype TokenProviderFunc func() (string, error)Function type implementing the AuthTokenProvider interface, enabling custom token provider behavior.
func (p TokenProviderFunc) GetToken() (string, error)Retrieves the authorization token by calling the underlying function.
Returns:
string: The authorization tokenerror: Error if token retrieval failsExample:
tokenProvider := endpointcreds.TokenProviderFunc(func() (string, error) {
// Read token from secure storage
token, err := readTokenFromVault()
if err != nil {
return "", err
}
return token, nil
})
provider := endpointcreds.New(
"http://localhost:8080/credentials",
func(o *endpointcreds.Options) {
o.AuthorizationTokenProvider = tokenProvider
},
)The provider can be configured using environment variables:
AWS_CONTAINER_AUTHORIZATION_TOKEN: Static authorization tokenAWS_CONTAINER_AUTHORIZATION_TOKEN_FILE: Path to file containing authorization token (refreshed on each request)When using AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE, the token file is read before each credential request, allowing token rotation without restarting the application.
The provider handles several error scenarios:
Example:
creds, err := provider.Retrieve(ctx)
if err != nil {
// Check for specific error types
if strings.Contains(err.Error(), "401") {
log.Fatal("Authorization failed - invalid token")
}
log.Fatalf("Failed to retrieve credentials: %v", err)
}This provider is commonly used with Amazon ECS tasks. ECS provides an endpoint for task role credentials:
import (
"os"
"github.com/aws/aws-sdk-go-v2/credentials/endpointcreds"
)
func main() {
// ECS provides credentials endpoint via environment variable
endpoint := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
if endpoint != "" {
endpoint = "http://169.254.170.2" + endpoint
}
provider := endpointcreds.New(endpoint)
// Use provider
}Use CredentialsCache: Wrap the provider with aws.CredentialsCache to handle automatic refresh of expiring credentials
provider := endpointcreds.New(endpoint)
creds := aws.NewCredentialsCache(provider)Secure endpoints: Use HTTPS for credential endpoints in production to protect credentials in transit
Token rotation: Use AuthorizationTokenProvider for dynamic token loading when tokens need rotation
Timeouts: Set appropriate HTTP client timeouts to prevent hanging requests:
customClient := &http.Client{Timeout: 5 * time.Second}
provider := endpointcreds.New(endpoint, func(o *endpointcreds.Options) {
o.HTTPClient = customClient
})Error handling: Implement proper error handling for network failures and invalid responses
Retry configuration: Configure appropriate retry behavior for transient failures:
import "github.com/aws/aws-sdk-go-v2/aws/retry"
provider := endpointcreds.New(endpoint, func(o *endpointcreds.Options) {
o.Retryer = retry.NewStandard()
})Expiration field is present in the response, credentials never expireExpiration is present, aws.CredentialsCache automatically refreshes credentials before they expire