首页 > 解决方案 > AWS Golang 开发工具包是否包含对 Cognito 提供程序的支持?

问题描述

我之前一直在使用 AWS 移动开发工具包和 AWS Cognito。所以我有一个配置有 2 个 AWS IAM 角色(经过身份验证和未经身份验证)的 AWS Cognito 身份池。通过它,我目前正在调用一些 AWS Lambda 函数。(顺便说一句,我知道 AWS API Gateway)

我现在正在尝试对 Go/Golang 客户端做类似的事情,即从客户端 Go 调用 AWS Lambda(未经身份验证的角色),但我找不到示例。

我找到了这个信息,但它似乎只是用于调用服务功能(即使用环境配置的秘密等,类似于 CLI)

https://docs.aws.amazon.com/sdk-for-go/api/service/cognitoidentity/#New

我还查看了 Go AWS SDK 源(凭证),它几乎就像 Cognito Provider 选项已从 SDK 中排除?而且我找不到任何似乎提到'identityPoolId'的东西。

如果是这种情况,我可以在不使用 SDK 的情况下以某种方式连接到 Go 中的 Javascript 公开接口吗?

https://docs.aws.amazon.com/cognito/latest/developerguide/getting-credentials.html#getting-credentials-1.javascript

虽然我想我也需要在没有 Javascript SDK 的情况下这样做......

即对 AWS 后端的直接 HTTPS 调用?AWS Cognito 服务是否以这种方式公开?

标签: amazon-web-servicesgoamazon-cognito

解决方案


这是我在开发类似应用程序(从 Go Lambda 访问用户池)时发现有用的帖子:https ://benincosa.com/?p=3714

他的例子应该在球场上(至少为你指明前进的方向)。

TLDR,适应

创建会话:

ses, _ := session.NewSession(&aws.Config{Region: aws.String("us-east-1")})

从提供者进行身份验证:

params := &cognitoidentityprovider.InitiateAuthInput{
        AuthFlow: aws.String("USER_PASSWORD_AUTH"),
        AuthParameters: map[string]*string{
                "USERNAME": aws.String("maria@vontropps.com"),
                "PASSWORD": aws.String("doremefasolatido"),
        },
        ClientId: aws.String("123456789abcdefghijklmnopq"),
}
cip := cognitoidentityprovider.New(ses)
authResp, _ := cip.InitiateAuth(params)

获取身份:

   svc := cognitoidentity.New(ses)
   idRes, _ := svc.GetId(&cognitoidentity.GetIdInput{
           IdentityPoolId: aws.String("us-east-1:123456789-444-4444-123456789abc"),
           Logins: map[string]*string{
                   "cognito-idp.<reg>.amazonaws.com/us-east-1_<id>": authResp.AuthenticationResult.IdToken,
           },
   })

   credRes, _ := svc.GetCredentialsForIdentity(&cognitoidentity.GetCredentialsForIdentityInput{
           IdentityId: idRes.IdentityId,
           Logins: map[string]*string{
                   "cognito-idp.<reg>.amazonaws.com/us-east-1_<id>": authResp.AuthenticationResult.IdToken,
           },
   })

调用api:

   url := "fill in your endpoint"
   client := new(http.Client)
   req, _ := http.NewRequest("GET", url, nil)

符号:

   v := v4.NewSigner(credentials.NewStaticCredentials(
          *credRes.Credentials.AccessKeyId,
          *credRes.Credentials.SecretKey,
          *credRes.Credentials.SessionToken,
   ))

   v.Sign(req, nil, "execute-api", "us-east-1", time.Now())

做出回应:

   resp, _ := client.Do(req)

处理响应:

   b, _ := ioutil.ReadAll(resp.Body)
   resp.Body.Close()
   fmt.Printf("%s\n", b)

推荐阅读