Невозможно создать AWS Cognito Identity Pool - PullRequest
0 голосов
/ 17 июня 2019

Я пытаюсь создать стек, который создаст пул пользователей с его клиентом приложения и пул удостоверений. Вот стек:

{
    "AWSTemplateFormatVersion": "2010-09-09",

    "Parameters" : {
        "CognitoUserPoolName": {
            "Description": "Name of the Cognito user pool as a parameter passed into this template.",
            "Type": "String"
        }
    },

    "Resources": {
        "UserPool": {
            "Type": "AWS::Cognito::UserPool",
            "Properties": {
                "UserPoolName" : {
                    "Ref": "CognitoUserPoolName"
                },
                "Policies": {
                    "PasswordPolicy": {
                        "MinimumLength": 8,
                        "RequireUppercase": true,
                        "RequireLowercase": true,
                        "RequireNumbers": true,
                        "RequireSymbols": true
                    }
                },
                "Schema": [
                    {
                        "Name": "name",
                        "AttributeDataType": "String",
                        "Mutable": true,
                        "Required": false
                    },
                    {
                        "Name": "email",
                        "AttributeDataType": "String",
                        "Mutable": false,
                        "Required": true
                    },
                    {
                        "Name": "phone_number",
                        "AttributeDataType": "String",
                        "Mutable": false,
                        "Required": false
                    }
                ],
                "LambdaConfig": {},
                "AutoVerifiedAttributes": [
                    "email"
                ],
                "UsernameAttributes": [
                    "email"
                ],
                "SmsVerificationMessage": "Your verification code is {####}. ",
                "EmailVerificationMessage": "Your app verification code is {####}. ",
                "EmailVerificationSubject": "Your app verification code",
                "SmsAuthenticationMessage": "Your authentication code is {####}. ",
                "MfaConfiguration": "OFF",
                "EmailConfiguration": {},
                "UserPoolTags": {},
                "AdminCreateUserConfig": {
                    "AllowAdminCreateUserOnly": false,
                    "UnusedAccountValidityDays": 7,
                    "InviteMessageTemplate": {
                        "SMSMessage": "Your username is {username} and temporary password is {####}. ",
                        "EmailMessage": "Your username is {username} and temporary password is {####}. ",
                        "EmailSubject": "Your temporary password"
                    }
                }         
            }
        },
        "UserPoolClient": {
            "Type": "AWS::Cognito::UserPoolClient",
            "Description": "App Client.",
            "DependsOn": "UserPool",
            "Properties": {
                "ClientName": {
                    "Fn::Sub": "${CognitoUserPoolName}Client"
                },
                "ExplicitAuthFlows": [
                    "ADMIN_NO_SRP_AUTH"
                ],
                "GenerateSecret": false,
                "RefreshTokenValidity": 30,
                "UserPoolId": {
                    "Ref": "UserPool"
                }
            }
        },
        "IdentityPool": {
            "Type" : "AWS::Cognito::IdentityPool",
            "DependsOn": ["UserPool", "UserPoolClient"],
            "Properties" : {
                "AllowUnauthenticatedIdentities" : false,
                "CognitoIdentityProviders" : [
                    {
                        "ClientId": {
                            "Ref": "UserPool"
                        },
                        "ProviderName": {
                            "Fn::GetAtt": [
                                "UserPool",
                                "Arn"
                            ]
                        }
                    }
                ],
                "IdentityPoolName" : {
                    "Fn::Sub": "${CognitoUserPoolName}IdentityPool"
                }
            }
        }
    },
    "Outputs": {
        "UserPoolARN": {
            "Value": {
                "Fn::GetAtt": [
                    "UserPool",
                    "Arn"
                ]
            }
        }
    }
}

И я продолжаю получать эту ошибку:

dentityPool CREATE_FAILED   1 validation error detected: Value 'us-east-1_<>' at 'cognitoIdentityProviders.1.member.clientId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w_]+ (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: ValidationException; Request ID: <>)

Похоже, формат User Pool ID неверный.

Я пытался отредактировать CognitoIdentityProviders следующим образом:

"CognitoIdentityProviders" : [
                    {
                        "ClientId": {
                            "Ref": "UserPool"
                        }
                    },
                    {
                        "ClientId": {
                            "Ref": "UserPoolClient"
                        }
                    }
                ],

Но я продолжаю получать ту же ошибку. Раньше я использовал консоль для создания пула удостоверений, вы должны добавить и User Pool ID и App Client ID, а User Pool ID имеет формат us-east-1-1_string.

Обновление 18 июня

Следуя ответу Дженса ниже, я смог создать пул удостоверений. Тем не менее, User Pool ID и App client id имеют значение User Pool ID: us-east-1-1_string.

Я пытался добавить другого провайдера, подобного этому:

"ClientId": {
                            "Ref": "UserPoolClient"
                        },
                        "ProviderName": {
                            "Fn::GetAtt": [
                                "UserPool",
                                "ProviderName"
                            ]
                        }

и он создал правильных провайдеров:

  • User Pool ID: us-east-1-1_string. например: us-east-1_Ab129faBb
  • App client id: string. например: 7lhlkkfbfb4q5kpp90urffao

    но есть дубликат провайдеров. Я пытался

  • измените App client id, имя провайдера на UserPoolClient, но создать не удалось.

  • удалить ProviderName из App client id, но создать не удалось.

Ответы [ 2 ]

1 голос
/ 17 июня 2019

Похоже, что это ошибка в реализации CloudFormation.

Если вы измените ClientID с us-east-1-1_string на us_east_1_1_string, шаблон будет создан, и пользовательский интерфейс покажет правильную исходную строку (с черточками).

Поскольку CloudFormation также не имеет функции замены, единственный способ заменить строку - это разделение и повторное соединение частей строки.

Таким образом, для 3 тире вам понадобится следующая конструкция:

"ClientId": {
  "Fn::Join": ["_",
    [{"Fn::Select": ["0",{"Fn::Split": ["-",{ "Ref": "UserPool"}]}]},
    {"Fn::Select": ["1",{"Fn::Split": ["-",{ "Ref": "UserPool"}]}]},
    {"Fn::Select": ["2",{"Fn::Split": ["-",{ "Ref": "UserPool"}]}]},
    {"Fn::Select": ["3",{"Fn::Split": ["-",{ "Ref": "UserPool"}]}]}
    ] 
  ]
}

Я пытался выполнить ваш шаблон, и он всегда генерировал для меня строку с двумя штрихами. Так что для версии с двумя тире это будет полный шаблон:

{
    "AWSTemplateFormatVersion": "2010-09-09",

    "Parameters": {
        "CognitoUserPoolName": {
            "Description": "Name of the Cognito user pool as a parameter passed into this template.",
            "Type": "String"
        }
    },

    "Resources": {
        "UserPool": {
            "Type": "AWS::Cognito::UserPool",
            "Properties": {
                "UserPoolName": {
                    "Ref": "CognitoUserPoolName"
                },
                "Policies": {
                    "PasswordPolicy": {
                        "MinimumLength": 8,
                        "RequireUppercase": true,
                        "RequireLowercase": true,
                        "RequireNumbers": true,
                        "RequireSymbols": true
                    }
                },
                "Schema": [{
                        "Name": "name",
                        "AttributeDataType": "String",
                        "Mutable": true,
                        "Required": false
                    },
                    {
                        "Name": "email",
                        "AttributeDataType": "String",
                        "Mutable": false,
                        "Required": true
                    },
                    {
                        "Name": "phone_number",
                        "AttributeDataType": "String",
                        "Mutable": false,
                        "Required": false
                    }
                ],
                "LambdaConfig": {},
                "AutoVerifiedAttributes": [
                    "email"
                ],
                "UsernameAttributes": [
                    "email"
                ],
                "SmsVerificationMessage": "Your verification code is {####}. ",
                "EmailVerificationMessage": "Your app verification code is {####}. ",
                "EmailVerificationSubject": "Your app verification code",
                "SmsAuthenticationMessage": "Your authentication code is {####}. ",
                "MfaConfiguration": "OFF",
                "EmailConfiguration": {},
                "UserPoolTags": {},
                "AdminCreateUserConfig": {
                    "AllowAdminCreateUserOnly": false,
                    "UnusedAccountValidityDays": 7,
                    "InviteMessageTemplate": {
                        "SMSMessage": "Your username is {username} and temporary password is {####}. ",
                        "EmailMessage": "Your username is {username} and temporary password is {####}. ",
                        "EmailSubject": "Your temporary password"
                    }
                }
            }
        },
        "UserPoolClient": {
            "Type": "AWS::Cognito::UserPoolClient",
            "Description": "App Client.",
            "DependsOn": "UserPool",
            "Properties": {
                "ClientName": {
                    "Fn::Sub": "${CognitoUserPoolName}Client"
                },
                "ExplicitAuthFlows": [
                    "ADMIN_NO_SRP_AUTH"
                ],
                "GenerateSecret": false,
                "RefreshTokenValidity": 30,
                "UserPoolId": {
                    "Ref": "UserPool"
                }
            }
        },
        "IdentityPool": {
            "Type": "AWS::Cognito::IdentityPool",
            "DependsOn": ["UserPool", "UserPoolClient"],
            "Properties": {
                "AllowUnauthenticatedIdentities": false,
                "CognitoIdentityProviders": [{
                    "ClientId": {
                      "Fn::Join": [
                        "_",
                        [
                            {
                                "Fn::Select": [
                                    "0",
                                    {
                                        "Fn::Split": [
                                            "-",
                                            {
                                                "Ref": "UserPool"
                                            }
                                        ]
                                    }
                                ]
                            },
                            {
                                "Fn::Select": [
                                    "1",
                                    {
                                        "Fn::Split": [
                                            "-",
                                            {
                                                "Ref": "UserPool"
                                            }
                                        ]
                                    }
                                ]
                            },
                            {
                                "Fn::Select": [
                                    "2",
                                    {
                                        "Fn::Split": [
                                            "-",
                                            {
                                                "Ref": "UserPool"
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    ]
                    },
                    "ProviderName": {
                        "Fn::GetAtt": [
                            "UserPool",
                            "ProviderName"
                        ]
                    }
                }],
                "IdentityPoolName": {
                    "Fn::Sub": "${CognitoUserPoolName}IdentityPool"
                }
            }
        }
    },
    "Outputs": {
        "UserPoolARN": {
            "Value": {
                "Fn::GetAtt": [
                    "UserPool",
                    "Arn"
                ]
            }
        }
    }
}
0 голосов
/ 18 июня 2019

Большое спасибо ответу @jens выше. Это сработало, хотя у него есть проблема с App client id, упомянутым выше в моем обновлении, это помогло мне найти правильный шаблон.

Я понял, как правильно написать шаблон:

"CognitoIdentityProviders": [
    {
        "ClientId": {
            "Ref": "UserPoolClient"
        },
        "ProviderName": {
            "Fn::GetAtt": [
                "UserPool",
                "ProviderName"
            ]
        }
    }
],

Таким образом, стек правильно создает Identity Pool. Документы AWS сбивают с толку:

ProviderName Имя поставщика для пула пользователей Amazon Cognito. Например, cognito-idp.us-east-2.amazonaws.com/us-east-2_123456789.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...