为了账号安全,请及时绑定邮箱和手机立即绑定

如何:使用 golang 客户端调用具有 IAM 授权的 API 网关端点

如何:使用 golang 客户端调用具有 IAM 授权的 API 网关端点

Go
翻翻过去那场雪 2023-01-03 10:11:29
看起来很简单,但我还无法弄清楚。在如下代码中 -resp, err := http.Get("API Gateway endpoint url goes here")if err != nil {   log.Fatalln(err)}我不确定如何告诉 http.get 使用 AWS 身份验证。aws cli 在主机上配置了访问密钥和秘密。所以我不想在代码中再次提及。一些帖子提到了签名请求。但我不确定这是否是正确的方法。鉴于 golang 中的 AWS SDK,这感觉有点低级。我希望AWS SDK 中必须有一种方法可以封装签名 HTTP 请求等并完成这项工作必须有一种方法可以通过“以某种方式”附加 aws creds 使用 http inbuild 包来执行此操作。非常感谢任何帮助!谢谢桑迪普
查看完整描述

1 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

一些帖子提到了签名请求。但我不确定这是否是正确的方法

是的,IAM Auth 需要请求签名(请参阅此处此处的文档)。当前方法是Signature v4如果 Api Gateway 具有预期的标头,则它会接受请求。“签名”是添加正确标头的过程:

# signature is derived from your secret key and the request contents.

--header 'Authorization: AWS4-HMAC-SHA256 Credential=AKIASIAXTWO8D5GSN4CS/20220712/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date, Signature=f2d8478ceff83d5cd0696502cb58a8331304846d11367d74608295c7acbfba0c'

# date prevents third parties from intercepting your request and resubmitting it later

--header 'X-Amz-Date: 20220712T124302Z'

AWS SDK 中必须有一种方法可以封装签名 HTTP 请求等并完成这项工作

对于多种语言(JS、Java 等,但不是 Go),get-sdk命令可以为您的 Rest API 生成一个SDK 客户端,除了其他便利之外,它还包装了签名过程:client.privateGet(params, body, additionalParams).

必须有一种方法可以通过“以某种方式”附加 aws creds 使用 http inbuild 包来做到这一点

使用普通的旧 SDK,添加标头需要做更多的工作,可以轻松包装为可重用的类型:

ctx := context.TODO()


// define the request

endpoint := "https://cbi3vltq21.execute-api.us-east-1.amazonaws.com"

u, _ := url.ParseRequestURI(endpoint)

u.Path = "prod/private"

req, _ := http.NewRequest("GET", u.String(), nil)


// get the credentials from the local config files

cfg, _ := config.LoadDefaultConfig(ctx,

  config.WithRegion("us-east-1"),

  config.WithSharedConfigProfile("my-profile"))

creds, _ :=  cfg.Credentials.Retrieve(ctx) 


// hash the request body - hex value used in the signature

hash := sha256.Sum256([]byte("")) // if the request has no body, use the empty string

hexHash := fmt.Sprintf("%x", hash)


// add the Authorization and X-Amz-Date headers to the request

signer := v4.NewSigner()

_ = signer.SignHTTP(ctx, creds, req, hexHash, "execute-api", cfg.Region, time.Now())


// execute the request

client := &http.Client{}

resp, _ := client.Do(req)

H/T 这个SO answer



查看完整回答
反对 回复 2023-01-03
  • 1 回答
  • 0 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信