Thomas Jaeger
Thomas Jaeger

Reputation: 943

How to signup a user with AWS Cognito and a console .NET Core 2.0?

I'm trying to signup a user with AWS Cognito with my .net core 2.0 console app and a user pool. My app crashes when this line gets executed:

var result = await _client.SignUpAsync(signUpRequest);

The frustrating part is that no exception is rasied. My console app just stops working under Visual Studio 2017. No errors, nothing. So, I tried to setup AWS SDK logging with log4net but the only thing that gets logged is my own log info entry. HELP!!!! Super frustrating.

Here is the Program.cs portion to setup logging:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]

namespace ASSA
{
    class Program
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static readonly ILoggerRepository repo = LogManager.GetRepository(Assembly.GetEntryAssembly());

        static void Main(string[] args)
        {
            if (repo.Configured)
                Console.WriteLine("configured");

            AWSConfigs.AWSRegion = "us-east-1";
            AWSConfigs.LoggingConfig.LogTo = LoggingOptions.Log4Net;
            AWSConfigs.LoggingConfig.LogResponses = ResponseLoggingOption.Always;

            log.Info("Started ASSA...");
            ShowMenu();
            WaitForMenuSelection();
        }

Here is the SignUpUser method:

    public async Task<bool> SignUpUser(string username, string password, string email, string phoneNumber, string firstName, string lastName)
    {
        try
        {
            var signUpRequest = new SignUpRequest
            {
                ClientId = CLIENT_ID,
                Username = username,
                Password = password
            };

            var attributeType = new AttributeType
            {
                Name = "phone_number",
                Value = phoneNumber
            };
            signUpRequest.UserAttributes.Add(attributeType);

            var attributeType1 = new AttributeType
            {
                Name = "email",
                Value = email
            };
            signUpRequest.UserAttributes.Add(attributeType1);

            var attributeType2 = new AttributeType
            {
                Name = "given_name",
                Value = firstName
            };
            signUpRequest.UserAttributes.Add(attributeType2);

            var attributeType3 = new AttributeType
            {
                Name = "family_name",
                Value = lastName
            };
            signUpRequest.UserAttributes.Add(attributeType3);

            var result = await _client.SignUpAsync(signUpRequest);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return false;
        }
        return true;
    }

Here is how I setup the credentials:

            try
        {
            BasicAWSCredentials creds = null;

            var chain = new CredentialProfileStoreChain();
            if (chain.TryGetAWSCredentials("Thomas", out var awsCredentials))
            {
                creds = new BasicAWSCredentials(awsCredentials.GetCredentials().AccessKey, awsCredentials.GetCredentials().SecretKey);
            }

            _client = new AmazonCognitoIdentityProviderClient(creds, Amazon.RegionEndpoint.USEast1);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

It crashes on line:

var result = await _client.SignUpAsync(signUpRequest);

Any help would be appreciated.

Upvotes: 3

Views: 2680

Answers (1)

Thomas Jaeger
Thomas Jaeger

Reputation: 943

The problem I had is that I was not involving the Cognito user pool during the sign-up process. The code include some links to read more about it.

Here is the code that does work:

        public async void SignUpNewUser(string userId, string email, string password, string familyName, string firstName, string phoneNumber, string deviceId)
    {
        AnonymousAWSCredentials credentials = new AnonymousAWSCredentials();
        provider = new AmazonCognitoIdentityProviderClient(credentials, RegionEndpoint.USEast1);
        pool = new CognitoUserPool(Globals.USER_POOL_ID, Globals.APP_CLIENT_ID, provider, "");

        // Based on latest user pool API
        // https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html
        // https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerificationMessageTemplateType.html

        // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html

        Dictionary<string, string> userAttributes = new Dictionary<string, string>(StringComparer.Ordinal)
        {
            { CognitoConstants.UserAttrEmail, email},
            { "family_name", familyName},
            { "given_name", firstName},
            { "phone_number", phoneNumber},
            { "custom:device_id", deviceId }
        };
        Dictionary<string, string> validationData = new Dictionary<string, string>(StringComparer.Ordinal)
        {
            { CognitoConstants.UserAttrEmail, email}
        };

        await pool.SignUpAsync(email, password, userAttributes, validationData).ConfigureAwait(false);

    }

Upvotes: 4

Related Questions