drn61317 2019-05-16 07:29
浏览 188
已采纳

具有Go的IAM身份验证的API网关HTTP客户端请求

Hello StackOverflow AWS Gophers,

I'm implementing a CLI with the excellent cobra/viper packages from spf13. We have an Athena database fronted by an API Gateway endpoint, which authenticates with IAM.

That is, in order to interact with its endpoints by using Postman, I have to define AWS Signature as Authorization method, define the corresponding AWS id/secret and then in the Headers there will be X-Amz-Security-Token and others. Nothing unusual, works as expected.

Since I'm new to Go, I was a bit shocked to see that there are no examples to do this simple HTTP GET request with the aws-sdk-go itself... I'm trying to use the shared credentials provider (~/.aws/credentials), as demonstrated for the S3 client Go code snippets from re:Invent 2015:

req := request.New(nil)

How can I accomplish this seemingly easy feat in 2019 without having to resort to self-cooked net/http and therefore having to manually read ~/.aws/credentials or worse, go with os.Getenv and other ugly hacks?

Any Go code samples interacting as client would be super helpful. No Golang Lambda/server examples, please, there's plenty of those out there.

  • 写回答

3条回答 默认 最新

  • doudong1117 2019-05-17 03:18
    关注

    The solution below uses 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)
    ", err)
                return
            }
    
            res, err := http.DefaultClient.Do(req)
            if err != nil {
                fmt.Printf("failed to call remote service: (%v)
    ", err)
                return
            }
    
            defer res.Body.Close()
            if res.StatusCode != 200 {
                fmt.Printf("service returned a status not 200: (%d)
    ", res.StatusCode)
                return
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器