登录
首页 >  Golang >  Go问答

测试 AWS 上的非法登录

来源:stackoverflow

时间:2024-03-06 18:27:27 143浏览 收藏

本篇文章向大家介绍《测试 AWS 上的非法登录》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

将 golang 与 go-aws-sdk 结合使用,在捕获无效会话凭据时遇到一些问题。

使用 ~/.aws/{config,credentials} 中的共享凭证文件

sess, err := session.newsessionwithoptions(session.options{
    profile: instance.config.aws.awsprofile,
})

当凭证有效时工作正常,但如果我在凭证文件中使用无效的 aws_access_key_id,我需要一种方法来使用我的 awslogin() 函数检测到这一点。

所发生的情况是,在使用上述 sess 时,对 aws 服务的任何后续调用都会引发恐慌。

如何使用上述 newsessionwithoptions() 方法检测失败的登录?

更新:是的,错误类型为 nil,因此以下内容没有用:

if err != nil {
        return nil, fmt.Errorf("Error logging into AWS: %v", err.Error())
    }

解决方案


这就是我最终所做的。测试凭证是否已加载,测试已知服务,例如此应用程序需要访问的 s3 存储桶。

// login to AWS
AWSProfile := "default"
fmt.Printf("Using AWS Profile: %v\n", instance.Config.AWS.AWSProfile)
Sess, err := session.NewSessionWithOptions(session.Options{
    Profile: AWSProfile,
})
if err != nil {
    return fmt.Errorf("Error logging into AWS: %v", err.Error())
}

// attempt to load config (e.g. env variables, shared config, instance profile) 
// log which AWS API Key is being used
svc := s3.New(Sess)
credentials, err := svc.Config.Credentials.Get()
if err != nil {
    return errors.New("Error logging into AWS. Check Credentials.")
}
fmt.Printf("Using Access Key ID: (%v)\n", credentials.AccessKeyID)
bucketName := "s3bucketname"

// test the login can access a typical aws service (s3) and known bucket 
params := &s3.ListObjectsInput {
    Bucket: aws.String(bucketName),
}
resp, _ := svc.ListObjects(params)

if len(resp.Contents) < 1 {
    return nil, fmt.Errorf("Error logging into AWS. Can not access bucket (%v). Check Credentials.", bucketName)
}

因此,在调用 aws 后,您必须检查是否存在无效错误。尝试使用 Credentials.Get() 看看是否 err != nil

以上就是《测试 AWS 上的非法登录》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>