or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

credentials.mdec2rolecreds.mdendpointcreds.mdindex.mdlogincreds.mdprocesscreds.mdssocreds.mdstscreds.md
tile.json

ssocreds.mddocs/

AWS SSO Credentials Provider

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

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"
)

Overview

The SSO credentials provider integrates with AWS Single Sign-On to retrieve temporary credentials. It handles:

  • Token Management: Caches SSO access tokens and automatically refreshes expired tokens
  • Credential Exchange: Exchanges SSO tokens for temporary AWS credentials
  • Role Access: Retrieves credentials for specific AWS accounts and IAM roles
  • Token Lifecycle: Monitors token expiration and refreshes transparently

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.

Usage Example

Basic Usage

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
}

With Token Provider

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
}

With Shared AWS Config

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
}

API Reference

Constants

const ProviderName = "SSOProvider"

Provider name identifier used to specify the source of credentials.

StandardCachedTokenFilepath

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 path

Example:

// 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....json

New

func New(client GetRoleCredentialsAPIClient, accountID, roleName, startURL string, optFns ...func(options *Options)) *Provider

Returns a new AWS SSO credential provider.

Parameters:

  • client (GetRoleCredentialsAPIClient): API client configured for the SSO user portal region
  • accountID (string): AWS account ID assigned to the user
  • roleName (string): IAM role name assigned to the user
  • startURL (string): URL to the organization's AWS SSO user portal
  • optFns (...func(options *Options)): Functional options for configuration

Returns:

  • *Provider: New SSO credentials provider

Example:

ssoClient := sso.New(sso.Options{Region: "us-east-1"})

provider := ssocreds.New(
    ssoClient,
    "123456789012",
    "DeveloperRole",
    "https://my-sso-portal.awsapps.com/start",
)

Options

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>.json
  • SSOTokenProvider (*SSOTokenProvider): Optional token provider for token refresh and management
  • CredentialSources ([]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
    },
)

Provider

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.

Retrieve

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 timeouts

Returns:

  • aws.Credentials: Retrieved temporary credentials
  • error: Error if retrieval fails

Example:

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)

ProviderSources

func (p *Provider) ProviderSources() []aws.CredentialSource

Returns the credential chain that was used to construct this provider.

Returns:

  • []aws.CredentialSource: Credential source chain for debugging

InvalidTokenError

type InvalidTokenError struct {
    Err error
}

Error type returned when a loaded token has expired or is invalid.

Fields:

  • Err (error): Underlying error

Error

func (i *InvalidTokenError) Error() string

Returns the error message.

Returns:

  • string: Error message

Example:

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())
    }
}

Unwrap

func (i *InvalidTokenError) Unwrap() error

Returns the underlying error wrapped by InvalidTokenError.

Returns:

  • error: Underlying error

SSOTokenProvider

type 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.

NewSSOTokenProvider

func NewSSOTokenProvider(client CreateTokenAPIClient, cachedTokenFilepath string, optFns ...func(o *SSOTokenProviderOptions)) *SSOTokenProvider

Returns 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 file
  • optFns (...func(o *SSOTokenProviderOptions)): Functional options for configuration

Returns:

  • *SSOTokenProvider: Initialized SSO token provider

Example:

ssoOIDCClient := ssooidc.New(ssooidc.Options{
    Region: "us-east-1",
})

tokenPath, _ := ssocreds.StandardCachedTokenFilepath("https://my-sso-portal.awsapps.com/start")

tokenProvider := ssocreds.NewSSOTokenProvider(
    ssoOIDCClient,
    tokenPath,
)

RetrieveBearerToken

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 timeouts

Returns:

  • bearer.Token: SSO bearer token for API authentication
  • error: Error if token cannot be retrieved or refreshed

Example:

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)

SSOTokenProviderOptions

type SSOTokenProviderOptions struct {
    Client              CreateTokenAPIClient
    ClientOptions       []func(*ssooidc.Options)
    CachedTokenFilepath string
}

Configuration options for SSOTokenProvider.

Fields:

  • Client (CreateTokenAPIClient): Client for SSOOIDC token operations
  • ClientOptions ([]func(*ssooidc.Options)): API client options for CreateToken operation
  • CachedTokenFilepath (string): Path to cached SSO token file

CreateTokenAPIClient

type 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 token

GetRoleCredentialsAPIClient

type 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 SSO

Prerequisites

Before using the SSO credentials provider:

  1. AWS SSO Configured: SSO must be configured in your AWS organization
  2. AWS CLI: Install and authenticate with the AWS CLI to cache the SSO token
    aws sso login --profile my-profile
  3. Shared Config: Configure AWS profile in ~/.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-1
  4. Token Cache: The SSO token must be cached by AWS CLI before this provider can use it

Token Cache Location

SSO tokens are cached in the following location:

~/.aws/sso/cache/<sha1-hex>.json

The 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"
}

Error Handling

Common error scenarios:

  • InvalidTokenError: Token has expired or is invalid, user must re-authenticate
  • Token file not found: Token cache doesn't exist or path is incorrect
  • Network errors: Unable to reach AWS SSO service
  • Invalid account/role: Account ID or role name doesn't exist or user doesn't have access

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)
}

Integration with AWS CLI

The AWS CLI automatically uses SSO credentials when configured:

  1. Configure profile:

    aws configure sso
  2. Login to SSO:

    aws sso login --profile my-profile
  3. Use 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.

Best Practices

  1. Wrap with CredentialsCache: Always wrap the provider with aws.CredentialsCache for automatic refresh

    provider := ssocreds.New(client, accountID, roleName, startURL)
    creds := aws.NewCredentialsCache(provider)
  2. Use shared configuration: Prefer loading credentials through config.LoadDefaultConfig() which handles SSO automatically

    cfg, err := config.LoadDefaultConfig(context.Background())
  3. Token security: Protect cached token files with appropriate permissions

    chmod 600 ~/.aws/sso/cache/*.json
  4. Handle 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
        }
    }
  5. 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)
  6. 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
        },
    )
  7. 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)
  8. 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
    }

Credential Lifecycle

  1. User authenticates with AWS SSO via aws sso login
  2. AWS CLI caches SSO token in ~/.aws/sso/cache/
  3. Provider reads cached SSO token from filesystem
  4. Provider exchanges SSO token for temporary AWS credentials
  5. Credentials are returned with expiration time
  6. CredentialsCache automatically refreshes before expiration
  7. SSOTokenProvider refreshes SSO token when it expires
  8. If SSO token expires, user must run aws sso login again

Comparison with Other Credential Providers

FeatureSSOLoginEC2 RoleSTS
AuthenticationSSO portalOAuth2 via aws loginIAM roleAssumeRole
Use caseEnterprise SSOLogin sessionsEC2 instancesRole assumption
Token typeSSO access tokenOAuth2 tokenTemporary credsSTS credentials
ConfigurationAWS Config profileSession-basedNone requiredSTS client
Cache location~/.aws/sso/cache~/.aws/sso/cacheN/AN/A
RefreshAutomatic via providerManual via aws loginAutomatic via IMDSAutomatic via STS

Configuration via AWS Shared Config

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-1

Then use with the SDK:

cfg, err := config.LoadDefaultConfig(
    context.Background(),
    config.WithSharedConfigProfile("dev"),
)