サードパーティのIdPからCognitoにSignUpできるようにする場合、特定のドメインのメールアドレスといったような制限をかけたいことがある。 PreSignUp時のLambdaでこれを弾いてやることでUserPoolに入らないようにすることができる。
Lambda
CognitoEventUserPoolsPreSignupを受け取って返す。
package main
import (
"errors"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func handler(event events.CognitoEventUserPoolsPreSignup) (events.CognitoEventUserPoolsPreSignup, error) {
fmt.Printf("PreSignup of user: %s\n", event.UserName)
if event.Request.UserAttributes["email"] != "[email protected]" {
return event, errors.New("Forbidden")
}
return event, nil
}
func main() {
lambda.Start(handler)
}
リソース
UserPoolのLambdaConfigでトリガーを設定できる。 CognitoからLambdaを呼べるPermissionが必要。
UserPool:
Type: AWS::Cognito::UserPool
Properties:
...
LambdaConfig:
PreSignUp: !GetAtt PresignupLambdaFunction.Arn
UserPoolLambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:invokeFunction
Principal: cognito-idp.amazonaws.com
FunctionName: !GetAtt PresignupLambdaFunction.Arn
SourceArn: arn:aws:cognito-idp:<region>:<account_id>:userpool/*
なおALBのActionでCognito認証を入れると登録失敗時に500エラーになってしまう。これを回避するには自前でやるしかないのかもしれない。
LambdaとALBでCognito認証をかけて失敗したらログイン画面に飛ばす - sambaiz-net
API GatewayでCognitoの認証をかけて必要ならログイン画面に飛ばす処理をGoで書く - sambaiz-net