登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-23 19:27:36 238浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《使用 Go 进行 IAM 身份验证的 API 网关 HTTP 客户端请求》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

您好 stackoverflow aws gophers,

我正在使用 spf13 中优秀的 cobra/viper 软件包实现 cli。我们有一个以 api 网关端点为前端的 athena 数据库,该端点通过 iam 进行身份验证。

也就是说,为了使用 postman 与其端点进行交互,我必须将 aws signature 定义为授权方法,定义相应的 aws id/secret,然后在标头中将有 x-amz-security-token 和其他的。没有什么异常,按预期工作。

由于我是 go 新手,我有点震惊地发现没有示例可以使用 aws-sdk-go 本身执行这个简单的 http get 请求...我正在尝试使用共享凭据提供程序 (~/.aws/credentials),如 re:invent 2015 中的 s3 客户端 go 代码片段所示:

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):

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`
}

下面的解决方案使用 aws-sdk-go-v2 https://github.com/aws/aws-sdk-go-v2

// A AWS SDK session is created because the HTTP API is secured using a
// IAM authorizer. As such, we need AWS client credentials and a
// session to properly sign the request.
cfg, err := external.LoadDefaultAWSConfig(
    external.WithSharedConfigProfile(profile),
)
if err != nil {
    fmt.Println("unable to create an AWS session for the provided profile")
    return
}


req, _ := http.NewRequest(http.MethodGet, "", nil)
req = req.WithContext(ctx)
signer := v4.NewSigner(cfg.Credentials)
_, err = signer.Sign(req, nil, "execute-api", cfg.Region, time.Now())
if err != nil {
    fmt.Printf("failed to sign request: (%v)\n", err)
    return
}

res, err := http.DefaultClient.Do(req)
if err != nil {
    fmt.Printf("failed to call remote service: (%v)\n", err)
    return
}

defer res.Body.Close()
if res.StatusCode != 200 {
    fmt.Printf("service returned a status not 200: (%d)\n", res.StatusCode)
    return
}

好了,本文到此结束,带大家了解了《使用 Go 进行 IAM 身份验证的 API 网关 HTTP 客户端请求》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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