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

logincreds.mddocs/

AWS Login Session Credentials Provider

Package: github.com/aws/aws-sdk-go-v2/credentials/logincreds

The logincreds package provides credential management for sessions created via the aws login command using cached OAuth2 tokens.

Import

import (
    "github.com/aws/aws-sdk-go-v2/credentials/logincreds"
    "github.com/aws/aws-sdk-go-v2/service/signin"
)

Overview

This provider retrieves temporary AWS credentials by exchanging cached OAuth2 tokens from aws login sessions. The AWS CLI must be used first to perform the login flow and cache the OAuth2 token.

Important: This provider does NOT initiate or perform the AWS login flow. The login must be completed using the AWS CLI before this provider can retrieve credentials.

Usage Example

Basic Usage

package main

import (
    "context"
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/credentials/logincreds"
    "github.com/aws/aws-sdk-go-v2/service/signin"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

func main() {
    // Get cached token filepath
    tokenPath, err := logincreds.StandardCachedTokenFilepath("my-session", "")
    if err != nil {
        panic(err)
    }

    // Create sign-in client
    signinClient := signin.New(signin.Options{
        Region: "us-east-1",
    })

    // Create login credentials provider
    provider := logincreds.New(signinClient, tokenPath)

    // Wrap with CredentialsCache
    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 Custom Options

provider := logincreds.New(
    signinClient,
    tokenPath,
    func(o *logincreds.Options) {
        o.ClientOptions = []func(*signin.Options){
            func(so *signin.Options) {
                so.Region = "us-west-2"
            },
        }
    },
)

API Reference

Constants

const ProviderName = "LoginProvider"

Provider name identifier for login credentials.

StandardCachedTokenFilepath

func StandardCachedTokenFilepath(session, dir string) (string, error)

Returns the filepath for the cached login token file using a SHA256 hash of the session identifier.

Parameters:

  • session (string): The session identifier used to compute the token filename
  • dir (string): Override root directory for token cache. Empty string defaults to ~/.aws/sso/cache

Returns:

  • string: The complete filepath to the cached token file
  • error: Error if filepath cannot be determined

Example:

// Use default cache directory (~/.aws/sso/cache)
tokenPath, err := logincreds.StandardCachedTokenFilepath("my-session", "")
if err != nil {
    log.Fatal(err)
}

// Use custom cache directory
tokenPath, err := logincreds.StandardCachedTokenFilepath("my-session", "/custom/cache/dir")
if err != nil {
    log.Fatal(err)
}

New

func New(client TokenAPIClient, path string, opts ...func(*Options)) *Provider

Returns a new login session credentials provider.

Parameters:

  • client (TokenAPIClient): Token API client for OAuth2 token operations
  • path (string): Path to the cached login token file
  • opts (...func(*Options)): Functional options for configuration

Returns:

  • *Provider: New login credentials provider

Example:

signinClient := signin.New(signin.Options{Region: "us-east-1"})
tokenPath := "/path/to/cached/token"

provider := logincreds.New(signinClient, tokenPath)

Options

type Options struct {
    Client            TokenAPIClient
    ClientOptions     []func(*signin.Options)
    CachedTokenFilepath string
    CredentialSources []aws.CredentialSource
}

Configuration options for the Provider.

Fields:

  • Client (TokenAPIClient): Token API client for credential operations
  • ClientOptions ([]func(*signin.Options)): API options to pass to the underlying CreateOAuth2Token operation
  • CachedTokenFilepath (string): Path to the cached login token file
  • CredentialSources ([]aws.CredentialSource): Credential chain information for reporting (not meant to be set directly)

Provider

type Provider struct {
    // Has unexported fields
}

Supplies credentials for an aws login session.

Retrieve

func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error)

Generates a new set of temporary credentials using an aws login session.

Parameters:

  • ctx (context.Context): Context for the request, supports cancellation and timeouts

Returns:

  • aws.Credentials: Generated temporary credentials
  • error: Error if credential generation fails

Example:

creds, err := provider.Retrieve(context.TODO())
if err != nil {
    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

TokenAPIClient

type TokenAPIClient interface {
    CreateOAuth2Token(context.Context, *signin.CreateOAuth2TokenInput, ...func(*signin.Options)) (*signin.CreateOAuth2TokenOutput, error)
}

Interface for the login session's token retrieval operation.

Methods:

  • CreateOAuth2Token: Creates an OAuth2 token for the login session

Prerequisites

Before using this provider, you must:

  1. Install AWS CLI: The provider relies on credentials cached by the AWS CLI
  2. Run aws login: Execute aws login to authenticate and cache the OAuth2 token
  3. Token file location: The cached token must exist at the specified path

Error Handling

Common error scenarios:

  • Token file not found: The cached token file doesn't exist or path is incorrect
  • Token expired: The cached OAuth2 token has expired and needs refreshing via aws login
  • Invalid token: The token file is malformed or corrupted
  • Network errors: Unable to reach the sign-in service

Example:

creds, err := provider.Retrieve(ctx)
if err != nil {
    if strings.Contains(err.Error(), "no such file") {
        log.Fatal("Token file not found. Run 'aws login' first.")
    }
    if strings.Contains(err.Error(), "expired") {
        log.Fatal("Token expired. Run 'aws login' to refresh.")
    }
    log.Fatalf("Failed to retrieve credentials: %v", err)
}

Token Cache Location

The standard cache location follows this pattern:

~/.aws/sso/cache/<sha256-hex-encoded-session>.json

The token filename is computed as the SHA256 hash of the session identifier, hex-encoded.

Integration with AWS Config

When using AWS shared configuration, login credentials can be configured in the profile:

[profile dev]
sso_session = my-session
sso_account_id = 123456789012
sso_role_name = DeveloperRole

[sso-session my-session]
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_region = us-east-1

Best Practices

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

    provider := logincreds.New(client, tokenPath)
    creds := aws.NewCredentialsCache(provider)
  2. Check token expiration: Implement checks for expired tokens and guide users to re-login

  3. Error messages: Provide clear error messages directing users to run aws login when tokens are missing or expired

  4. Session management: Use descriptive session identifiers for easier token management

  5. Token security: The cached token files contain sensitive data. Ensure proper file permissions:

    chmod 600 ~/.aws/sso/cache/*.json
  6. Token refresh workflow: Implement a workflow to detect token expiration and prompt for re-authentication:

    creds, err := provider.Retrieve(ctx)
    if err != nil {
        if isTokenExpired(err) {
            fmt.Println("Token expired. Please run 'aws login' to refresh.")
            os.Exit(1)
        }
        log.Fatal(err)
    }

Credential Lifecycle

  1. User runs aws login via AWS CLI
  2. AWS CLI performs OAuth2 flow and caches token
  3. Provider reads cached token from filesystem
  4. Provider calls CreateOAuth2Token to exchange token for temporary credentials
  5. Temporary credentials are returned with expiration time
  6. CredentialsCache automatically refreshes before expiration
  7. If token expires, user must run aws login again

Comparison with SSO Credentials

Featurelogincredsssocreds
AuthenticationOAuth2 via aws loginSSO access token
Token formatOAuth2 tokenSSO access token
Use caseLogin sessionsSSO integration
ConfigurationSession-basedProfile-based with sso_session