使用 Go 进行 IAM 身份验证的 API 网关 HTTP 客户端请求

2024-03-25

您好 StackOverflow AWS Gophers,

我正在实施 https://github.com/umccr/cliCLI 具有出色的spf13 的 cobra/viper 软件包 https://github.com/spf13/cobra。我们有一个以 API 网关端点为前端的 Athena 数据库,该端点通过 IAM 进行身份验证。

也就是说,为了使用 Postman 与其端点交互,我必须定义AWS Signature作为授权方法,定义相应的AWS id/secret,然后在标头中会有X-Amz-Security-Token和别的。没有什么异常,按预期工作。

由于我是 Go 新手,我有点震惊地发现没有示例可以使用以下命令执行这个简单的 HTTP GET 请求aws-sdk-go本身...我正在尝试使用共享凭据提供程序(~/.aws/credentials),如 S3 客户端所示re:Invent 2015 中的 Go 代码片段 https://youtu.be/iOGIKG3EptI?t=634:

req := request.New(nil)

2019年我怎样才能完成这个看似简单的壮举,而不必诉诸自煮net/http因此必须手动读取~/.aws/credentials或者更糟,一起去os.Getenv和其他丑陋的黑客?

任何交互的 Go 代码示例作为客户会非常有帮助的。请不要提供 Golang Lambda/服务器示例,那里有很多示例。


不幸的是,自从编写了接受的答案以来,该库似乎已经更新,并且解决方案不再相同。经过一番尝试和错误后,这似乎是处理签名的最新方法(使用https://pkg.go.dev/github.com/aws/aws-sdk-go-v2 https://pkg.go.dev/github.com/aws/aws-sdk-go-v2):

import (
    "context"
    "net/http"
    "time"

    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)

func main() {
    // Context is not being used in this example.
    cfg, err := config.LoadDefaultConfig(context.TODO())

    if err != nil {
        // Handle error.
    }

    credentials, err := cfg.Credentials.Retrieve(context.TODO())

    if err != nil {
        // Handle error.
    }

    // The signer requires a payload hash. This hash is for an empty payload.
    hash := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
    req, _ := http.NewRequest(http.MethodGet, "api-gw-url", nil)
    signer := v4.NewSigner()
    err = signer.SignHTTP(context.TODO(), credentials, req, hash, "execute-api", cfg.Region, time.Now())

    if err != nil {
        // Handle error.
    }

    // Use `req`
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Go 进行 IAM 身份验证的 API 网关 HTTP 客户端请求 的相关文章

随机推荐