Francis Lewis
Francis Lewis

Reputation: 8980

Getting InvalidToken "The provided token is malformed or otherwise invalid" when using GetObjectInput

Following the AWS documentation to the letter on how to download an object from S3, I'm getting the The provided token is malformed or otherwise invalid error.

I'm running my code through the AWS SAM CLI.

My code is:

    sess, _ := session.NewSession(&aws.Config{
        Region: aws.String(endpoints.UsWest2RegionID),
    })

    svc := s3.New(sess)

    aak := os.Getenv("AWS_ACCESS_KEY")
    ask := os.Getenv("AWS_SECRET_KEY")
    fmt.Println("aak", aak, "ask", ask) // both of these correctly show my keys are being passed in

    resp, err := svc.GetObject(&s3.GetObjectInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
    })

    if err != nil {
        fmt.Println(err)
    }

I'm running it with: sam local invoke LambdaMyFunction --debug -e test/event.json

I verified that the AWS Access and Secret keys are correct. I verified that I can download the object through CLI: aws s3api get-object --bucket "mybucket-dev" --key "mydir/mykey_test.json" result.txt

result.txt is populated with the contents of mykey_test.json, so I know my creds have access to the file. I'm assuming the issue has to do with the role that lambda uses not having access to the file? But I can't find enough info to verify that possibility, or how to solve the problem testing locally.

Upvotes: 1

Views: 7011

Answers (2)

Carl
Carl

Reputation: 79

If your SSO,, the, for windows, in a command prompt.. aws sso login --profile then used sam local invoke 'HelloWorldFunction' --profile and it works (no Invalid Token error...

Upvotes: 0

Francis Lewis
Francis Lewis

Reputation: 8980

Turns out the AWS_SESSION_TOKEN was being passed in string (null), which is definitely not a valid session token. So my code looks like this:

os.Setenv("AWS_SESSION_TOKEN", "")
sess, _ := session.NewSession()

And now I'm able to successfully download the file.

Since we don't yet know how this will be passed in through actual lambda, I set a check on it that looks like this:

    // this is STUPID!!! But necessary.
    if os.Getenv("AWS_SESSION_TOKEN") == "(null)" {
        os.Setenv("AWS_SESSION_TOKEN", "")
    }
    sess, _ := session.NewSession()

Upvotes: 3

Related Questions