Package: github.com/aws/aws-sdk-go-v2/credentials/ssocreds
The ssocreds package provides credential retrieval using AWS Single Sign-On (SSO) access tokens. It manages SSO token caching and automatic refresh, enabling seamless credential exchange for AWS API access.
import (
"github.com/aws/aws-sdk-go-v2/credentials/ssocreds"
"github.com/aws/aws-sdk-go-v2/service/sso"
"github.com/aws/aws-sdk-go-v2/service/ssooidc"
)The SSO credentials provider integrates with AWS Single Sign-On to retrieve temporary credentials. It handles:
Important: The Provider and SSOTokenProvider are not safe for concurrent use. Wrap Provider with aws.CredentialsCache and SSOTokenProvider with a token cache for production use.
package main
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials/ssocreds"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/sso"
)
func main() {
// Create SSO client for the organization's SSO region
ssoClient := sso.New(sso.Options{
Region: "us-east-1",
})
// Get cached token filepath
tokenPath, err := ssocreds.StandardCachedTokenFilepath("my-sso-start-url")
if err != nil {
panic(err)
}
// Create SSO credentials provider
provider := ssocreds.New(
ssoClient,
"123456789012", // AWS Account ID
"DeveloperRole", // IAM Role name
"https://my-sso-portal.awsapps.com/start", // SSO Start URL
)
// Wrap with CredentialsCache for caching and concurrency safety
credentials := aws.NewCredentialsCache(provider)
// Use with AWS service clients
cfg := aws.Config{
Region: "us-east-1",
Credentials: credentials,
}
client := s3.NewFromConfig(cfg)
// Use client
}package main
import (
"context"
"github.com/aws/aws-sdk-go-v2/credentials/ssocreds"
"github.com/aws/aws-sdk-go-v2/service/sso"
"github.com/aws/aws-sdk-go-v2/service/ssooidc"
)
func main() {
// Create clients
ssoClient := sso.New(sso.Options{
Region: "us-east-1",
})
ssoOIDCClient := ssooidc.New(ssooidc.Options{
Region: "us-east-1",
})
// Get token filepath
tokenPath, err := ssocreds.StandardCachedTokenFilepath("my-sso-start-url")
if err != nil {
panic(err)
}
// Create token provider for SSO token refresh
tokenProvider := ssocreds.NewSSOTokenProvider(ssoOIDCClient, tokenPath)
// Create credentials provider with token provider
provider := ssocreds.New(
ssoClient,
"123456789012",
"DeveloperRole",
"https://my-sso-portal.awsapps.com/start",
func(o *ssocreds.Options) {
o.SSOTokenProvider = tokenProvider
},
)
// Use provider
}package main
import (
"context"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
func main() {
// Load default config - automatically uses SSO credentials from profile
cfg, err := config.LoadDefaultConfig(
context.Background(),
config.WithSharedConfigProfile("my-profile"),
)
if err != nil {
panic(err)
}
// Create service client with SSO credentials
client := s3.NewFromConfig(cfg)
// Use client
}const ProviderName = "SSOProvider"Provider name identifier used to specify the source of credentials.
func StandardCachedTokenFilepath(key string) (string, error)Returns the standard filepath for a cached SSO token file using SHA1 hex encoding.
Parameters:
key (string): Key to compute SHA1 hash (typically the SSO start URL)Returns:
string: Filepath for cached SSO token (~/.aws/sso/cache/<sha1-hex>.json)error: Error if unable to derive the pathExample:
// Compute token filepath from SSO start URL
tokenPath, err := ssocreds.StandardCachedTokenFilepath("https://my-sso-portal.awsapps.com/start")
if err != nil {
log.Fatal(err)
}
fmt.Println(tokenPath) // ~/.aws/sso/cache/abc123def456....jsonfunc New(client GetRoleCredentialsAPIClient, accountID, roleName, startURL string, optFns ...func(options *Options)) *ProviderReturns a new AWS SSO credential provider.
Parameters:
client (GetRoleCredentialsAPIClient): API client configured for the SSO user portal regionaccountID (string): AWS account ID assigned to the userroleName (string): IAM role name assigned to the userstartURL (string): URL to the organization's AWS SSO user portaloptFns (...func(options *Options)): Functional options for configurationReturns:
*Provider: New SSO credentials providerExample:
ssoClient := sso.New(sso.Options{Region: "us-east-1"})
provider := ssocreds.New(
ssoClient,
"123456789012",
"DeveloperRole",
"https://my-sso-portal.awsapps.com/start",
)type Options struct {
Client GetRoleCredentialsAPIClient
AccountID string
RoleName string
StartURL string
CachedTokenFilepath string
SSOTokenProvider *SSOTokenProvider
CredentialSources []aws.CredentialSource
}Configuration options for the Provider.
Fields:
Client (GetRoleCredentialsAPIClient): AWS SSO client configured for the user portal region (required)AccountID (string): AWS account ID for role access (required)RoleName (string): IAM role name for access (required)StartURL (string): SSO user portal URL (required)CachedTokenFilepath (string): Path to cached token file. Defaults to ~/.aws/sso/cache/<sha1-hex>.jsonSSOTokenProvider (*SSOTokenProvider): Optional token provider for token refresh and managementCredentialSources ([]aws.CredentialSource): Credential chain information for reporting (not meant to be set directly)Example:
provider := ssocreds.New(
ssoClient,
"123456789012",
"DeveloperRole",
"https://my-sso-portal.awsapps.com/start",
func(o *ssocreds.Options) {
o.CachedTokenFilepath = "/custom/path/token.json"
o.SSOTokenProvider = customTokenProvider
},
)type Provider struct {
// Has unexported fields
}Retrieves temporary AWS credentials by exchanging an SSO access token for role credentials.
Note: Not safe for concurrent use. Wrap with aws.CredentialsCache for production use.
func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error)Retrieves temporary AWS credentials from SSO by exchanging the access token.
Parameters:
ctx (context.Context): Context for the request, supports cancellation and timeoutsReturns:
aws.Credentials: Retrieved temporary credentialserror: Error if retrieval failsExample:
creds, err := provider.Retrieve(context.TODO())
if err != nil {
if errors.As(err, &ssocreds.InvalidTokenError{}) {
log.Fatal("SSO token is invalid or expired")
}
log.Fatalf("Failed to retrieve credentials: %v", err)
}
fmt.Printf("Access Key: %s\n", creds.AccessKeyID)
fmt.Printf("Expires: %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 InvalidTokenError struct {
Err error
}Error type returned when a loaded token has expired or is invalid.
Fields:
Err (error): Underlying errorfunc (i *InvalidTokenError) Error() stringReturns the error message.
Returns:
string: Error messageExample:
creds, err := provider.Retrieve(ctx)
if err != nil {
var invalidErr *ssocreds.InvalidTokenError
if errors.As(err, &invalidErr) {
fmt.Printf("Token error: %v\n", invalidErr.Error())
}
}func (i *InvalidTokenError) Unwrap() errorReturns the underlying error wrapped by InvalidTokenError.
Returns:
error: Underlying errortype SSOTokenProvider struct {
// Has unexported fields
}Utility for refreshing SSO AccessTokens for Bearer Authentication. Manages cached SSO tokens and handles automatic refresh when expired.
Note: Not safe for concurrent use. Wrap with smithy-go's bearer token cache for production use.
func NewSSOTokenProvider(client CreateTokenAPIClient, cachedTokenFilepath string, optFns ...func(o *SSOTokenProviderOptions)) *SSOTokenProviderReturns an initialized SSOTokenProvider that periodically refreshes cached SSO tokens.
Parameters:
client (CreateTokenAPIClient): API client for token refresh (configured for SSO region)cachedTokenFilepath (string): Path to cached token fileoptFns (...func(o *SSOTokenProviderOptions)): Functional options for configurationReturns:
*SSOTokenProvider: Initialized SSO token providerExample:
ssoOIDCClient := ssooidc.New(ssooidc.Options{
Region: "us-east-1",
})
tokenPath, _ := ssocreds.StandardCachedTokenFilepath("https://my-sso-portal.awsapps.com/start")
tokenProvider := ssocreds.NewSSOTokenProvider(
ssoOIDCClient,
tokenPath,
)func (p SSOTokenProvider) RetrieveBearerToken(ctx context.Context) (bearer.Token, error)Returns SSO token from cached file, refreshing if expired. Used for Bearer token authentication.
Parameters:
ctx (context.Context): Context for the request, supports cancellation and timeoutsReturns:
bearer.Token: SSO bearer token for API authenticationerror: Error if token cannot be retrieved or refreshedExample:
token, err := tokenProvider.RetrieveBearerToken(context.TODO())
if err != nil {
log.Fatalf("Failed to retrieve token: %v", err)
}
fmt.Printf("Token: %s\n", token.Value)
fmt.Printf("Expires: %s\n", token.Expires)type SSOTokenProviderOptions struct {
Client CreateTokenAPIClient
ClientOptions []func(*ssooidc.Options)
CachedTokenFilepath string
}Configuration options for SSOTokenProvider.
Fields:
Client (CreateTokenAPIClient): Client for SSOOIDC token operationsClientOptions ([]func(*ssooidc.Options)): API client options for CreateToken operationCachedTokenFilepath (string): Path to cached SSO token filetype CreateTokenAPIClient interface {
CreateToken(context.Context, *ssooidc.CreateTokenInput, ...func(*ssooidc.Options)) (*ssooidc.CreateTokenOutput, error)
}Interface for SSOTokenProvider's CreateToken operation to refresh SSO tokens.
Methods:
CreateToken: Creates/refreshes SSO tokentype GetRoleCredentialsAPIClient interface {
GetRoleCredentials(context.Context, *sso.GetRoleCredentialsInput, ...func(*sso.Options)) (*sso.GetRoleCredentialsOutput, error)
}Interface for the GetRoleCredentials operation to retrieve role credentials from SSO.
Methods:
GetRoleCredentials: Retrieves role credentials from SSOBefore using the SSO credentials provider:
aws sso login --profile my-profile~/.aws/config
[profile my-profile]
sso_account_id = 123456789012
sso_role_name = DeveloperRole
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_region = us-east-1
region = us-east-1SSO tokens are cached in the following location:
~/.aws/sso/cache/<sha1-hex>.jsonThe token filename is computed as the SHA1 hex hash of the SSO start URL.
Example token file:
{
"accessToken": "...",
"clientId": "...",
"clientSecret": "...",
"expiresAt": "2024-01-15T10:30:00Z",
"refreshToken": "...",
"registrationExpiresAt": "2025-01-14T10:00:00Z",
"startUrl": "https://my-sso-portal.awsapps.com/start"
}Common error scenarios:
Example error handling:
creds, err := provider.Retrieve(ctx)
if err != nil {
var invalidErr *ssocreds.InvalidTokenError
if errors.As(err, &invalidErr) {
fmt.Println("Token expired. Please run 'aws sso login' to refresh.")
os.Exit(1)
}
if strings.Contains(err.Error(), "no such file") {
fmt.Println("Token file not found. Please run 'aws sso login' first.")
os.Exit(1)
}
log.Fatalf("Failed to retrieve credentials: %v", err)
}The AWS CLI automatically uses SSO credentials when configured:
Configure profile:
aws configure ssoLogin to SSO:
aws sso login --profile my-profileUse with AWS SDK:
cfg, err := config.LoadDefaultConfig(
context.Background(),
config.WithSharedConfigProfile("my-profile"),
)The SDK automatically detects and uses SSO credentials from your AWS configuration.
Wrap with CredentialsCache: Always wrap the provider with aws.CredentialsCache for automatic refresh
provider := ssocreds.New(client, accountID, roleName, startURL)
creds := aws.NewCredentialsCache(provider)Use shared configuration: Prefer loading credentials through config.LoadDefaultConfig() which handles SSO automatically
cfg, err := config.LoadDefaultConfig(context.Background())Token security: Protect cached token files with appropriate permissions
chmod 600 ~/.aws/sso/cache/*.jsonHandle token expiration: Implement logic to detect expired tokens and prompt re-authentication
creds, err := provider.Retrieve(ctx)
if err != nil {
var invalidErr *ssocreds.InvalidTokenError
if errors.As(err, &invalidErr) {
fmt.Println("Please run 'aws sso login' to refresh your credentials")
return err
}
}Context timeouts: Use appropriate context timeouts for SSO requests
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
creds, err := provider.Retrieve(ctx)Explicit token provider: For advanced scenarios, explicitly manage token refresh
tokenProvider := ssocreds.NewSSOTokenProvider(ssoOIDCClient, tokenPath)
provider := ssocreds.New(
ssoClient,
accountID,
roleName,
startURL,
func(o *ssocreds.Options) {
o.SSOTokenProvider = tokenProvider
},
)Bearer token cache: When using SSOTokenProvider standalone, wrap with bearer token cache for concurrency
import "github.com/aws/smithy-go/auth/bearer"
tokenProvider := ssocreds.NewSSOTokenProvider(client, tokenPath)
tokenCache := bearer.NewTokenCache(tokenProvider.RetrieveBearerToken)Multiple profiles: Support multiple SSO profiles with different caches
for _, profile := range profiles {
tokenPath, _ := ssocreds.StandardCachedTokenFilepath(profile.StartURL)
provider := ssocreds.New(client, profile.AccountID, profile.RoleName, profile.StartURL)
// Use provider for profile
}aws sso login~/.aws/sso/cache/aws sso login again| Feature | SSO | Login | EC2 Role | STS |
|---|---|---|---|---|
| Authentication | SSO portal | OAuth2 via aws login | IAM role | AssumeRole |
| Use case | Enterprise SSO | Login sessions | EC2 instances | Role assumption |
| Token type | SSO access token | OAuth2 token | Temporary creds | STS credentials |
| Configuration | AWS Config profile | Session-based | None required | STS client |
| Cache location | ~/.aws/sso/cache | ~/.aws/sso/cache | N/A | N/A |
| Refresh | Automatic via provider | Manual via aws login | Automatic via IMDS | Automatic via STS |
Configure SSO credentials in your AWS configuration file:
[profile dev]
sso_account_id = 123456789012
sso_role_name = DeveloperRole
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_region = us-east-1
region = us-east-1
[profile prod]
sso_account_id = 987654321098
sso_role_name = AdminRole
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_region = us-east-1
region = us-east-1Then use with the SDK:
cfg, err := config.LoadDefaultConfig(
context.Background(),
config.WithSharedConfigProfile("dev"),
)