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 (
"github.com/aws/aws-sdk-go-v2/credentials/logincreds"
"github.com/aws/aws-sdk-go-v2/service/signin"
)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.
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
}provider := logincreds.New(
signinClient,
tokenPath,
func(o *logincreds.Options) {
o.ClientOptions = []func(*signin.Options){
func(so *signin.Options) {
so.Region = "us-west-2"
},
}
},
)const ProviderName = "LoginProvider"Provider name identifier for login credentials.
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 filenamedir (string): Override root directory for token cache. Empty string defaults to ~/.aws/sso/cacheReturns:
string: The complete filepath to the cached token fileerror: Error if filepath cannot be determinedExample:
// 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)
}func New(client TokenAPIClient, path string, opts ...func(*Options)) *ProviderReturns a new login session credentials provider.
Parameters:
client (TokenAPIClient): Token API client for OAuth2 token operationspath (string): Path to the cached login token fileopts (...func(*Options)): Functional options for configurationReturns:
*Provider: New login credentials providerExample:
signinClient := signin.New(signin.Options{Region: "us-east-1"})
tokenPath := "/path/to/cached/token"
provider := logincreds.New(signinClient, tokenPath)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 operationsClientOptions ([]func(*signin.Options)): API options to pass to the underlying CreateOAuth2Token operationCachedTokenFilepath (string): Path to the cached login token fileCredentialSources ([]aws.CredentialSource): Credential chain information for reporting (not meant to be set directly)type Provider struct {
// Has unexported fields
}Supplies credentials for an aws login session.
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 timeoutsReturns:
aws.Credentials: Generated temporary credentialserror: Error if credential generation failsExample:
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)func (p *Provider) ProviderSources() []aws.CredentialSourceReturns the credential chain that was used to construct this provider.
Returns:
[]aws.CredentialSource: Credential source chain for debuggingtype 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 sessionBefore using this provider, you must:
aws login to authenticate and cache the OAuth2 tokenCommon error scenarios:
aws loginExample:
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)
}The standard cache location follows this pattern:
~/.aws/sso/cache/<sha256-hex-encoded-session>.jsonThe token filename is computed as the SHA256 hash of the session identifier, hex-encoded.
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-1Wrap with CredentialsCache: Always wrap the provider with aws.CredentialsCache for automatic refresh
provider := logincreds.New(client, tokenPath)
creds := aws.NewCredentialsCache(provider)Check token expiration: Implement checks for expired tokens and guide users to re-login
Error messages: Provide clear error messages directing users to run aws login when tokens are missing or expired
Session management: Use descriptive session identifiers for easier token management
Token security: The cached token files contain sensitive data. Ensure proper file permissions:
chmod 600 ~/.aws/sso/cache/*.jsonToken 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)
}aws login via AWS CLIaws login again| Feature | logincreds | ssocreds |
|---|---|---|
| Authentication | OAuth2 via aws login | SSO access token |
| Token format | OAuth2 token | SSO access token |
| Use case | Login sessions | SSO integration |
| Configuration | Session-based | Profile-based with sso_session |