GolangでAmazon Cognitoを使う

GolangでAmazon Cognitoを使う

こんにちは、Anti-Pattern Inc.の塚本です。

APIサーバからCognitoに接続して、ユーザー登録するユースケースの実装について書こうと思います。

Nuxt.jsでAmazon Cognitoを使う内容は、弊社メンバのkoooooheが書いてますので、どうぞ参考に!

https://medium.com/anti-pattern-engineering/nuxt-jsでcognitoを使う-cd011efa1b29

Configuring the AWS SDK for Goを利用して実装しました。

AdminCreateUserを発行したいのでちょっとだけ変更していますが、ほとんど、AWS Code Sampleが使えます。これはありがたい。

https://docs.aws.amazon.com/code-samples/latest/catalog/go-cognito-CognitoCreateUser.go.html

実装したプログラム

認証情報は環境変数に設定しているので、アプリケーションで設定していません。

https://github.com/aws/aws-sdk-go/blob/master/aws/session/env_config.go

import (
 "os"
 "github.com/aws/aws-sdk-go/aws"
 "github.com/aws/aws-sdk-go/aws/session"
 "github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
)
func CreateUser(email string) (*string, error) {
 sess := session.Must(session.NewSessionWithOptions(session.Options{
  SharedConfigState: session.SharedConfigEnable,
 }))
cognitoClient := cognitoidentityprovider.New(sess)
 newUserData := &cognitoidentityprovider.AdminCreateUserInput{
  // lambda param
  //ClientMetadata: map[string]*string{"test": &val},
DesiredDeliveryMediums: []*string{
   aws.String("EMAIL"),
  },
    
  UserAttributes: []*cognitoidentityprovider.AttributeType{
   {
    Name:  aws.String("email"),
    Value: aws.String(email),
   },
   {
    Name:  aws.String("custom:custom_parameter"),
    Value: aws.String("1"),
   }
  },
 }
  
 newUserData.SetUserPoolId(os.Getenv("POOL_ID"))
 newUserData.SetUsername(email)
ret, err := cognitoClient.AdminCreateUser(newUserData)
 if err != nil {
  return nil, err
 }
  
 for _, v := range ret.User.Attributes {
  if *v.Name == "sub" {
   return v.Value, nil
  }
 }
 return nil, err
}

まとめ

珍しく今回はハマってません。

ClientMetadataを何に使うのかパッと分からなかったのですが、Cognitoのユーザプールに設定するトリガーに渡せるパラメーターなんですね。こちらにしっかり書いてありました。

https://docs.aws.amazon.com/ja_jp/cognito/latest/developerguide/user-pool-lambda-post-authentication.html

ドキュメントが充実しているなーというのが今回の感想です。

こちらからは以上です!