ashish choudhary
ashish choudhary

Reputation: 359

is there a way to validate the credentials for aws account using aws-sdk-go

I am creating the session using the API provided in the aws-sdk-go.

Problem: If I provide the wrong credentials, then it will also create a session. But when I make some other API call using this sesssion, it will raise an error.

Is there any way we can validate the credentials before creating a session?

Session creation method:

var MyCredentials = credentials.NewStaticCredentials(access_key_id, secret_access_key, "")

var sess = session.Must(session.NewSession(&aws.Config{
    Credentials: MyCredentials,
    Region:      aws.String(hostRegion),
    MaxRetries:  aws.Int(3),
}))

Upvotes: 0

Views: 2004

Answers (3)

Hemant_Negi
Hemant_Negi

Reputation: 2068

To validate credentials you must call an AWS API. But you can check if a set of credentials were supplied to the application like below

// MustHaveCredentials looks for aws credentials using default credential provider chain as
// documented here https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html
func MustHaveCredentials() {
    _, err := defaults.CredChain(defaults.Get().Config, defaults.Get().Handlers).Get()
    if err != nil {
        log.Fatalf("no AWS credentials provided! %v", err)
    }
}

Upvotes: -1

Doug Schwartz
Doug Schwartz

Reputation: 95

When you create a session, the API does not talk to the server/service. All it knows is that you have some values like the ones I showed. Perhaps the easiest way to confirm is use the S3 HeadBucket command on a bucket that you know exists as it's about the lowest overhead call I know.

HTH,

doug

Upvotes: 1

Doug
Doug

Reputation: 46

What do you mean by "wrong credentials"? If the credentials are bogus, every call fails. If you mean that you have different profiles, create the session using the profile you specify in ~/.aws/credentials. For example, if I have the following in ~/.aws/credentials:

[default]
aws_access_key_id = ...
aws_secret_access_key = ...
[goober]
aws_access_key_id = ...
aws_secret_access_key = ...

I can use my default credentials when I create a session by:

sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

But if I want to use my goober profile (from https://docs.aws.amazon.com/sdk-for-go/api/aws/session/):

sess, err := session.NewSessionWithOptions(session.Options{ Profile: "goober", })

Upvotes: 1

Related Questions