Accessing AWS using go SDK v2 with local SSO token

150 views Asked by At

I have a simple AWS Go SDK v2 program

package main

import (
        "context"
        "encoding/json"
        "os"

        "github.com/aws/aws-sdk-go-v2/config"
        "github.com/aws/aws-sdk-go-v2/service/sts"
)

func main() {
    ctx := context.Background()
    cfg, err := config.LoadDefaultConfig(ctx)
    if err != nil {
        panic(err)
    }
    stsCli := sts.NewFromConfig(cfg)
    resp, err := stsCli.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{})
    if err != nil {
        panic(err)
    }
    _ = json.NewEncoder(os.Stdout).Encode(resp)
}

The request to STS fails:

sobug % go run ./test.go
panic: operation error STS: GetCallerIdentity, https response error StatusCode: 403, RequestID: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX, api error InvalidClientTokenId: The security token included in the request is invalid.

goroutine 1 [running]:
main.main()
    /tmp/sobug/test.go:49 +0x158
exit status 2

My company recently implemented AWS SSO. After executing aws sso login (using the default profile), there are no issues with the token while using the CLI:

sobug % aws sts get-caller-identity
{
    "UserId": "****",
    "Account": "****",
    "Arn": "arn:aws:sts::****:assumed-role/****/****"
}

But even though the SSO token is refreshed, I still get the same error from my SDK program.

~/.aws/config

[default]
region = ****
sso_session = ****
sso_account_id = ****
sso_role_name = ****
output = ****
[sso-session ****]
sso_start_url = ****
sso_region = ****
sso_registration_scopes = ****

What gives?

1

There are 1 answers

0
Matt Wlazlo On

It turns out I had credentials for both SSO and the regular AWS tokens in ~/.aws.

My summary is that if the CLI detects SSO token before regular credentials, whereas the SDK checks regular credentials before checking for SSO tokens.

SSO tokens are stored in ~/.aws/sso/cache while regular AWS tokens are stored in ~/.aws/credentials.

I solved my problem by simply removing the old ~/.aws/credentials file.

~/.aws/credentials

[default]
aws_access_key_id = ****
aws_secret_access_key = ****