예제 #1
0
        public override async Task Start(string _postJson, IDynamoDBContext _dynamoDBContext)
        {
            await base.Start(_postJson, _dynamoDBContext);

            User user          = JsonConvert.DeserializeObject <User>(_postJson);
            var  signUpRequest = new SignUpRequest
            {
                ClientId = ApiDefine.CognitoClientId,
                Password = user.Password,
                Username = user.Email
            };
            var emailAttribute = new AttributeType
            {
                Name  = "email",
                Value = user.Email
            };
            var nickNameAttribute = new AttributeType
            {
                Name  = "nickname",
                Value = user.Name
            };

            signUpRequest.UserAttributes.Add(emailAttribute);
            signUpRequest.UserAttributes.Add(nickNameAttribute);

            var client = new AmazonCognitoIdentityProviderClient(ApiDefine.Credentials, RegionEndpoint.USWest2);
            var result = await client.SignUpAsync(signUpRequest);

            JsPath = "cognito/sign.up.js";
            string json = JsonConvert.SerializeObject(result);

            await loadJs();

            ExecJs = ExecJs.Replace("JSON", json.Replace("\"", "\\\""));
        }
예제 #2
0
        public static async void AuthenticateWithSrpAsync(string email, string pass)
        {
            AmazonCognitoIdentityProviderConfig config = new AmazonCognitoIdentityProviderConfig();
            var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), Amazon.RegionEndpoint.EUWest1);
            var userPool = new CognitoUserPool(POOL_NAME, AWS_CLIENT_ID, provider);

            var user = new CognitoUser(email, AWS_CLIENT_ID, userPool, provider);

            AuthFlowResponse authResponse;

            try
            {
                InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
                {
                    Password = pass
                };

                authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
            }
            catch (Amazon.CognitoIdentityProvider.Model.NotAuthorizedException)
            {
                Console.WriteLine(email + " incorrect");
                return;
            }
            Console.WriteLine(authResponse);
        }
예제 #3
0
        public static async Task <AuthenticationResultType> RefreshTokenDaihuyen(AuthenticationResultType request)
        {
            try
            {
                var    accesstoken = new JwtSecurityToken(request.AccessToken);
                var    idtoken     = new JwtSecurityToken(request.IdToken);
                string userName    = idtoken.Claims.FirstOrDefault(m => m.Type.Equals("cognito:username"))?.Value;
                // get new token
                AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(_region);
                CognitoUserPool userPool = new CognitoUserPool(UserPoolId, _clientId, provider);
                CognitoUser     user     = new CognitoUser(userName, _clientId, userPool, provider, _clientSecret)
                {
                    SessionTokens = new CognitoUserSession(request.IdToken, request.AccessToken, request.RefreshToken, DateTime.Now, DateTime.Now.AddHours(1))
                };
                InitiateRefreshTokenAuthRequest refreshRequest = new InitiateRefreshTokenAuthRequest()
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
                };

                AuthFlowResponse authResponse = await user.StartWithRefreshTokenAuthAsync(refreshRequest);

                return(authResponse.AuthenticationResult);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
예제 #4
0
        private async Task <RespondToAuthChallengeResponse> VerifyChallenge(string username, string session, string accountId)
        {
            var provider = new AmazonCognitoIdentityProviderClient(RegionEndpoint.USEast2);

            try
            {
                var challengeRequest = new RespondToAuthChallengeRequest
                {
                    Session            = session,
                    ChallengeName      = "CUSTOM_CHALLENGE",
                    ClientId           = CLIENTAPP_ID,
                    ChallengeResponses = new Dictionary <string, string>()
                    {
                        { "ANSWER", accountId },
                        { "USERNAME", username }
                    }
                };

                return(await provider.RespondToAuthChallengeAsync(challengeRequest));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return(null);
        }
예제 #5
0
    internal async Task <CognitoUser> ValidateUser(string username, string password)
    {
        AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());

        CognitoUserPool userPool = new CognitoUserPool(this.POOL_ID, this.CLIENTAPP_ID, provider);

        CognitoUser            user        = new CognitoUser(username, this.CLIENTAPP_ID, userPool, provider);
        InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
        {
            Password = password
        };
        var adsadas = new InitiateAuthRequest();



        AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

        if (authResponse.AuthenticationResult != null)
        {
            return(user);
        }
        else
        {
            return(null);
        }
    }
        /// <summary>
        /// Registration Service constructor
        /// </summary>
        /// <param name="logger"></param>
        public RegistrationService(ILogger logger)
        {
            _logger = logger;
            //string join = Environment.GetEnvironmentVariables() is Dictionary<string, string> env ? string.Join(";", env?.Select(x => x.Key + "=" + x.Value)) : "Environment.GetEnvironmentVariables()=null";
            //_logger.LogInformation($"Environment:{join}");
            // Ensure all required environment variables are provided
            CognitoClientId = Environment.GetEnvironmentVariable(COGNITO_APPLICATION_CLIENT_ID_ENVIRONMENT_VARIABLE_LOOKUP);
            if (CognitoClientId == null)
            {
                throw new Exception($"Missing required environment variable {COGNITO_APPLICATION_CLIENT_ID_ENVIRONMENT_VARIABLE_LOOKUP}");
            }

            CognitoUserPoolId = Environment.GetEnvironmentVariable(COGNITO_USER_POOL_ID_ENVIRONMENT_VARIABLE_LOOKUP);
            if (CognitoUserPoolId == null)
            {
                throw new Exception($"Missing required environment variable {COGNITO_USER_POOL_ID_ENVIRONMENT_VARIABLE_LOOKUP}");
            }
            string region = Environment.GetEnvironmentVariable(COGNITO_REGION_ENVIRONMENT_VARIABLE_LOOKUP);

            if (region == null)
            {
                throw new Exception($"Missing required environment variable {COGNITO_REGION_ENVIRONMENT_VARIABLE_LOOKUP}");
            }

            var config = new AmazonCognitoIdentityProviderConfig
            {
                AuthenticationRegion = region,
                RegionEndpoint       = RegionEndpoint.GetBySystemName(region)
            };

            Cognito = new AmazonCognitoIdentityProviderClient(config);


            InitializeCustomAttributes().Wait();
        }
예제 #7
0
        private static async Task SignUpUser(string email, string password, string customerId)
        {
            IAmazonCognitoIdentityProvider provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), region);
            SignUpRequest signUpRequest             = new SignUpRequest()
            {
                ClientId = appClientId,
                Username = email,
                Password = password
            };

            List <AttributeType> attributes = new List <AttributeType>()
            {
                new AttributeType()
                {
                    Name = "email", Value = email
                },
                new AttributeType()
                {
                    Name = "custom:stripeId", Value = customerId
                }
            };

            signUpRequest.UserAttributes = attributes;

            try
            {
                SignUpResponse result = await provider.SignUpAsync(signUpRequest);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #8
0
        public async Task <object> CognitoSignIn(UserRequest creds)
        {
            string accessKey = Environment.GetEnvironmentVariable("ACCESS");
            string secretKey = Environment.GetEnvironmentVariable("SECRET");
            // string provider = Environment.GetEnvironmentVariable("PROVIDER");
            string poolId = Environment.GetEnvironmentVariable("POOL");
            string client = Environment.GetEnvironmentVariable("CLIENT");

            try{
                using var AmazonCognitoP = new AmazonCognitoIdentityProviderClient(
                          awsAccessKeyId: accessKey,
                          awsSecretAccessKey: secretKey,
                          region: RegionEndpoint.USEast1);

                var authReq = new AdminInitiateAuthRequest
                {
                    UserPoolId = poolId,
                    ClientId   = client,
                    AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
                };
                authReq.AuthParameters.Add("USERNAME", creds.userName);
                authReq.AuthParameters.Add("PASSWORD", creds.passWord);

                var authResp = await AmazonCognitoP.AdminInitiateAuthAsync(authReq);

                return(authResp);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #9
0
        /// <summary>
        /// Confirms user registration as an admin with using a confirmation code.
        /// </summary>
        /// <param name="loginRequest"></param>
        /// <returns></returns>
        public async Task <bool> AdminConfirmUserWithNewPassword(Real.AdminConfirmUserWithTempPasswordRequest loginRequest)
        {
            var client            = new AmazonCognitoIdentityProviderClient(RegionEndpoint.GetBySystemName(REGION));
            var dictTypeAuthParam = new Dictionary <string, string> {
                { "USERNAME", loginRequest.Username }, { "PASSWORD", loginRequest.TempPassword }
            };

            AdminInitiateAuthRequest req = new AdminInitiateAuthRequest()
            {
                AuthFlow       = new AuthFlowType(AuthFlowType.ADMIN_NO_SRP_AUTH),
                ClientId       = CLIENTAPP_ID,
                UserPoolId     = POOL_ID,
                AuthParameters = dictTypeAuthParam
            };

            var response = await client.AdminInitiateAuthAsync(req);

            var dictTypeChallangeResponse = new Dictionary <string, string>
            {
                { "USERNAME", loginRequest.Username },
                { "NEW_PASSWORD", loginRequest.NewPassword }
            };

            var respondRequest = new AdminRespondToAuthChallengeRequest()
            {
                ChallengeName      = new ChallengeNameType(ChallengeNameType.NEW_PASSWORD_REQUIRED),
                ClientId           = CLIENTAPP_ID,
                ChallengeResponses = dictTypeChallangeResponse,
                Session            = response.Session,
                UserPoolId         = POOL_ID
            };
            var respondResponse = await client.AdminRespondToAuthChallengeAsync(respondRequest);

            return(true);
        }
        public async Task <string> GetCredsAsync(string userPassword)
        {
            AmazonCognitoIdentityProviderClient provider =
                new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), regionEndpoint);
            CognitoUserPool        userPool    = new CognitoUserPool(poolId, clientId, provider);
            CognitoUser            user        = new CognitoUser(userId, clientId, userPool, provider);
            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = userPassword
            };

            try
            {
                authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

                accessToken  = authResponse.AuthenticationResult.AccessToken;
                refreshToken = authResponse.AuthenticationResult.RefreshToken;
                goodTill     = DateTime.UtcNow.AddSeconds(authResponse.AuthenticationResult.ExpiresIn);

                return(accessToken);
            }
            catch (Exception ex)
            {
                var x = ex.Message;
                throw;
            }
        }
        public async Task <string> RefreshCredsAsync()
        {
            AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient
                                                               (new AnonymousAWSCredentials(), regionEndpoint);
            CognitoUserPool userPool = new CognitoUserPool(poolId, clientId, provider);

            CognitoUser user = new CognitoUser(userId, clientId, userPool, provider);

            user.SessionTokens = new CognitoUserSession(null, null, authResponse.AuthenticationResult.RefreshToken, DateTime.Now, DateTime.Now.AddHours(1));

            InitiateRefreshTokenAuthRequest refreshRequest = new InitiateRefreshTokenAuthRequest()
            {
                AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
            };

            try
            {
                authResponse = await user.StartWithRefreshTokenAuthAsync(refreshRequest).ConfigureAwait(false);

                accessToken  = authResponse.AuthenticationResult.AccessToken;
                refreshToken = authResponse.AuthenticationResult.RefreshToken;
                goodTill     = DateTime.UtcNow.AddSeconds(authResponse.AuthenticationResult.ExpiresIn);
                return(accessToken);
            }
            catch (Exception ex)
            {
                var x = ex.Message;
                throw;
            }
        }
예제 #12
0
        private static void RegistrarCognitoConfig(IServiceCollection services)
        {
            services.AddCognitoIdentity(config =>
            {
                config.Password = new Microsoft.AspNetCore.Identity.PasswordOptions
                {
                    RequireDigit           = false,
                    RequiredLength         = 6,
                    RequiredUniqueChars    = 0,
                    RequireLowercase       = false,
                    RequireUppercase       = false,
                    RequireNonAlphanumeric = false
                };
            });

            var sp = services.BuildServiceProvider();
            var cognitoUserPoolConfigurations = (CognitoUserPoolConfigurationsDTO)sp
                                                .GetService(typeof(CognitoUserPoolConfigurationsDTO));


            var credentials = new BasicAWSCredentials(cognitoUserPoolConfigurations.AccessKey, cognitoUserPoolConfigurations.SecretKey);
            var provider    =
                new AmazonCognitoIdentityProviderClient(credentials, RegionEndpoint.GetBySystemName(cognitoUserPoolConfigurations.Region));

            services.AddSingleton <IAmazonCognitoIdentityProvider>(provider);

            var cognitoUserPool =
                new CognitoUserPool(
                    cognitoUserPoolConfigurations.PoolId,
                    cognitoUserPoolConfigurations.ClientId,
                    provider, cognitoUserPoolConfigurations.ClientSecretKey);

            services.AddSingleton(cognitoUserPool);
        }
예제 #13
0
    private async Task <string> GetCredsAsync(Config config)
    {
        AmazonCognitoIdentityProviderClient provider =
            new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.USEast2);
        CognitoUserPool        userPool    = new CognitoUserPool(config.userPoolId, config.userPoolClientId, provider);
        CognitoUser            user        = new CognitoUser(config.userId, config.userPoolClientId, userPool, provider);
        InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
        {
            Password = config.userPass
        };

        AuthFlowResponse context = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

        // TODO: Custom exceptions and handlers
        if (context.AuthenticationResult != null)
        {
            Console.WriteLine("Authentication success");
        }
        else
        {
            Console.WriteLine("Failed PSG authentication!");
        }

        credentials = user.GetCognitoAWSCredentials(config.identityPoolId, RegionEndpoint.USEast2);
        if (credentials != null)
        {
            Console.WriteLine("Acquired user credentials");
        }
        else
        {
            Console.WriteLine("Failed to acquire user credentials!");
        }

        return(context.AuthenticationResult.AccessToken);
    }
예제 #14
0
        public async Task <IActionResult> Register(UserToCreateRequest userToCreateRequest)
        {
            var _client = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.USEast1);
            // Register the user using Cognito
            var signUpRequest = new SignUpRequest
            {
                ClientId = "4s8cbl7ptf75hp2tbqc14coib7",
                Password = "******",
                Username = "******",
            };

            signUpRequest.UserAttributes.Add(new AttributeType {
                Name  = "phone_number",
                Value = "+84765998291"
            });

            signUpRequest.UserAttributes.Add(new AttributeType
            {
                Name  = "name",
                Value = "NguyenKhanhDuy"
            });

            var reponse = await _client.SignUpAsync(signUpRequest);

            return(Ok());
        }
예제 #15
0
        public async Task <String> AuthorizeUser()
        {
            try
            {
                AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
                CognitoUserPool userPool = new CognitoUserPool(ConfigurationManager.AppSettings["USERPOOL_ID"],
                                                               ConfigurationManager.AppSettings["CLIENT_ID"], provider);

                CognitoUser cognitoUser = new CognitoUser(inputEmail.Value, ConfigurationManager.AppSettings["CLIENT_ID"], userPool, provider);

                InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
                {
                    Password = inputPassword.Value
                };

                AuthFlowResponse authFlowResponse = await cognitoUser.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

                if (authFlowResponse.AuthenticationResult != null)
                {
                    return(authFlowResponse.AuthenticationResult.AccessToken);
                }
            }
            catch (Exception ex)
            {
                var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
                var script  = string.Format("alert({0});", message);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ex", "alert('" + ex.Message + "');", true);
            }
            return(null);
        }
예제 #16
0
        /// <summary>
        /// This send the temporary code again to the admin created user which is now not activate
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task <bool> ResendTemporaryPasssword(Real.ResendTemporaryCodeRequest request)
        {
            AmazonCognitoIdentityProviderClient provider =
                new AmazonCognitoIdentityProviderClient(RegionEndpoint.GetBySystemName(REGION));

            AdminCreateUserRequest userRequest = new AdminCreateUserRequest();

            userRequest.Username               = request.Username;
            userRequest.UserPoolId             = POOL_ID;
            userRequest.DesiredDeliveryMediums = new List <string>()
            {
                "EMAIL"
            };
            userRequest.MessageAction     = MessageActionType.RESEND;
            userRequest.TemporaryPassword = PasswordGenerator.GeneratePassword(true, true, true, true, false, 6);

            try
            {
                AdminCreateUserResponse response = await provider.AdminCreateUserAsync(userRequest);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
            return(true);
        }
예제 #17
0
    //Method that signs in Cognito user
    private async Task SignInUser()
    {
        string userName = UsernameField.text;
        string password = PasswordField.text;
        string email    = EmailField.text;

        AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Region);

        CognitoUserPool userPool = new CognitoUserPool(PoolID, AppClientID, provider);

        CognitoUser user = new CognitoUser(userName, AppClientID, userPool, provider);

        InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
        {
            Password = password
        };

        AuthFlowResponse authResponse = null;

        try
        {
            authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

            GetUserRequest getUserRequest = new GetUserRequest();
            getUserRequest.AccessToken = authResponse.AuthenticationResult.AccessToken;

            Debug.Log("User Access Token: " + getUserRequest.AccessToken);
            signInSuccessful = true;
        }
        catch (Exception e)
        {
            Debug.Log("EXCEPTION" + e);
            return;
        }
    }
예제 #18
0
        public async Task <CognitoContext> SignUp(string userName, string password)
        {
            try
            {
                var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint);

                var result = await provider.SignUpAsync(new SignUpRequest
                {
                    ClientId = ClientId,
                    Password = password,
                    Username = userName
                });

                Console.WriteLine("Signed in.");

                return(new CognitoContext(CognitoResult.SignupOk));
            }
            catch (UsernameExistsException ue)
            {
                return(new CognitoContext(CognitoResult.UserNameAlreadyUsed));
            }
            catch (InvalidParameterException ie)
            {
                return(new CognitoContext(CognitoResult.PasswordRequirementsFailed));
            }
            catch (Exception e)
            {
                Console.WriteLine($"SignIn() threw an exception {e}");
            }
            return(new CognitoContext(CognitoResult.Unknown));
        }
예제 #19
0
        private async Task <SignUpResponse> TrySignUpUser(ISignupModelUser user)
        {
            try
            {
                SignUpRequest request = GetSignUpRequest(user);
                AmazonCognitoIdentityProviderClient client = GetAmazonCognitoIdentity();
                SignUpResponse response = await client.SignUpAsync(request);

                return(response);
            }
            catch (UsernameExistsException e)
            {
                throw new WebApiException(System.Net.HttpStatusCode.Forbidden, e.Message);
            }
            catch (InvalidPasswordException e)
            {
                throw new WebApiException(System.Net.HttpStatusCode.BadRequest, e.Message);
            }
            catch (InvalidParameterException e)
            {
                throw new WebApiException(System.Net.HttpStatusCode.BadRequest, e.Message);
            }
            catch (Exception e)
            {
                throw new WebApiException(System.Net.HttpStatusCode.InternalServerError, e.Message);
            }
        }
예제 #20
0
        protected async Task <string> GetAccessToken(AuthenticationModel model)
        {
            string responseToken = String.Empty;

            try
            {
                AmazonCognitoIdentityProviderClient IdentityClientProvider = new AmazonCognitoIdentityProviderClient(
                    new AnonymousAWSCredentials(), RegionEndpoint.GetBySystemName(model.RegionEndpoint));
                CognitoUserPool UserPool = new CognitoUserPool(model.PoolId, model.ClientId, IdentityClientProvider);
                CognitoUser     user     = new CognitoUser(model.Username, model.ClientId, UserPool, IdentityClientProvider);
                var             response = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest { Password = model.Password }).ConfigureAwait(false);

                if (response.AuthenticationResult != null)
                {
                    responseToken = response.AuthenticationResult.AccessToken;
                    ExpiresIn     = response.AuthenticationResult.ExpiresIn - 300;
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            return(responseToken);
        }
예제 #21
0
        public async Task <string> SignIn(string username, string password)
        {
            var provider =
                new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials( ));

            var userPool    = new CognitoUserPool(UserPool, ClientId, provider);
            var user        = new CognitoUser(username, ClientId, userPool, provider);
            var authRequest = new InitiateSrpAuthRequest( )
            {
                Password = password
            };

            var authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

            // if the user has mfa enabled, this response will have a challenge attribute set accordingly. We would then need to branch based on the MFA type. The return type should probably be some type of object that has some field that says "tokenPresent"
            string retVal;

            if (string.IsNullOrWhiteSpace(authResponse.ChallengeName))
            {
                retVal = authResponse.AuthenticationResult.AccessToken;
            }
            else
            {
                retVal = authResponse.ChallengeName;
            }

            return(retVal);
        }
예제 #22
0
        private async Task <bool> CheckPasswordAsync(string userName, string password)
        {
            try
            {
                var client = new AmazonCognitoIdentityProviderClient();

                var authReq = new AdminInitiateAuthRequest
                {
                    UserPoolId = ConfigurationManager.AppSettings["USERPOOL_ID"],
                    ClientId   = ConfigurationManager.AppSettings["CLIENT_ID"],
                    AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
                };
                authReq.AuthParameters.Add("USERNAME", userName);
                authReq.AuthParameters.Add("PASSWORD", password);

                AdminInitiateAuthResponse authResp = await client.AdminInitiateAuthAsync(authReq);

                // Validate that there is no case that an exception won't be thrown

                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #23
0
    internal async Task <System.Net.HttpStatusCode> UpdateAttributes(UpdateUserAttributesRequest a)
    {
        AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
        UpdateUserAttributesResponse        resp     = await provider.UpdateUserAttributesAsync(a);

        return(resp.HttpStatusCode);
    }
예제 #24
0
        /// <summary>
        ///     Get refreshed token from Cognito using for the current user
        /// </summary>
        /// <param name="userRequest"></param>
        /// <returns>AuthFlowResponse</returns>
        public AuthFlowResponse ProcessRefreshToken(UserRequest userRequest)
        {
            AuthFlowResponse authResponse;

            try
            {
                AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USWest2);
                CognitoUserPool userPool = new CognitoUserPool("XXX_XXX", userRequest.CognitoClientId, provider);
                CognitoUser     user     = new CognitoUser(userRequest.UserName, userRequest.CognitoClientId, userPool, provider, userRequest.ClientSecret)
                {
                    SessionTokens = new CognitoUserSession(null, null, userRequest.Payload.RefreshToken, DateTime.Now, DateTime.Now.AddDays(10))
                };

                InitiateRefreshTokenAuthRequest authRequest = new InitiateRefreshTokenAuthRequest()
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN
                };
                authResponse = user.StartWithRefreshTokenAuthAsync(authRequest).Result;
                return(authResponse);
            }
            catch (Exception processRefreshTokenException)
            {
                LambdaLogger.Log(processRefreshTokenException.ToString());
                return(null);
            }
        }
예제 #25
0
        static void Main(string[] args)
        {
            string CLIENT_ID   = "";
            string USERPOOL_ID = "";
            string USERNAME    = "";
            string PASSWORD    = "";
            string SECRET      = "";

            AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(FallbackRegionFactory.GetRegionEndpoint());

            var request = new AdminInitiateAuthRequest()
            {
                AuthFlow   = AuthFlowType.ADMIN_USER_PASSWORD_AUTH,
                ClientId   = CLIENT_ID,
                UserPoolId = USERPOOL_ID,
            };

            //aws cognito-idp admin-set-user-password --user-pool-id us-east-1_GKvnPcxax --username awshero --password Pass@word1234 --permanent

            request.AuthParameters.Add("USERNAME", USERNAME);
            request.AuthParameters.Add("PASSWORD", PASSWORD);
            request.AuthParameters.Add("SECRET_HASH", GenerateSecretHash(USERNAME, CLIENT_ID, SECRET));
            var response = provider.AdminInitiateAuthAsync(request).Result;

            Console.WriteLine(response.AuthenticationResult.AccessToken);
            Console.ReadLine();
        }
        private async Task <string> CheckPasswordAsync(string userName, string password)
        {
            try
            {
                string accessKey = WebConfigurationManager.AppSettings["AWSAccessKeyId"];
                string secretKey = WebConfigurationManager.AppSettings["AWSSecretAccessKey"];
                //string _aWSRegion = ConfigurationManager.AppSettings["AWSRegion"];

                AmazonCognitoIdentityProviderClient _client = new AmazonCognitoIdentityProviderClient(accessKey, secretKey, Amazon.RegionEndpoint.USEast1);
                var authReq = new AdminInitiateAuthRequest
                {
                    UserPoolId = WebConfigurationManager.AppSettings["USERPOOL_ID"],
                    ClientId   = WebConfigurationManager.AppSettings["CLIENT_ID"],
                    AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
                };
                authReq.AuthParameters.Add("USERNAME", userName);
                authReq.AuthParameters.Add("PASSWORD", password);

                AdminInitiateAuthResponse authResp = await _client.AdminInitiateAuthAsync(authReq);

                string IdToken = authResp.AuthenticationResult.IdToken;
                return(IdToken);
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }
        }
예제 #27
0
        //Login
        private async Task <AuthFlowResponse> AuthenticateWithSrpAsync(string userName, string password)
        {
            AuthFlowResponse authResponse = null;
            var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), FallbackRegionFactory.GetRegionEndpoint());
            var userPool = new CognitoUserPool(ConfigData.UserPoolId, ConfigData.ClientId, provider);

            this.User = new CognitoUser(userName, ConfigData.ClientId, userPool, provider);

            try
            {
                authResponse = await this.User.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
                {
                    Password = password
                }).ConfigureAwait(false);

                if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                {
                    authResponse = await this.User.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                    {
                        SessionID   = authResponse.SessionID,
                        NewPassword = ""
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(authResponse);
        }
예제 #28
0
        protected async void Page_Load(object sender, EventArgs e)
        {
            try

            {
                if (("log_out").Equals(Request.QueryString["mode"]))
                {
                    if (HttpContext.Current.Application["AccessToken"] != null)
                    {
                        AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
                        GlobalSignOutRequest globalSignOutRequest    = new GlobalSignOutRequest()
                        {
                            AccessToken = HttpContext.Current.Application["AccessToken"].ToString()
                        };
                        await provider.GlobalSignOutAsync(globalSignOutRequest);

                        HttpContext.Current.Application["AccessToken"] = null;
                        Response.Redirect("Default.aspx");
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('Token not detected');" +
                                                                "window.location.href='Login.aspx';", true);
                    }
                }
            }
            catch (Exception ex)
            {
                var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
                var script  = string.Format("alert({0});", message);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ex", script, true);
            }
        }
예제 #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <Models.MongoDatabaseSettings>(
                Configuration.GetSection(nameof(Models.MongoDatabaseSettings)));

            services.AddSingleton <IMongoDatabaseSettings>(sp =>
                                                           sp.GetRequiredService <IOptions <Models.MongoDatabaseSettings> >().Value);
            services.AddSingleton <UserDetailsService>();

            services.Configure <StripeOptions>(options =>
            {
                options.PublishableKey = "";
                options.SecretKey      = "";
                options.WebhookSecret  = "";
                options.BasicPrice     = "";
                options.ProPrice       = "";
                options.Domain         = "http://localhost:4242";
            });
            services.AddTransient <MySqlDatabase>(_ => new MySqlDatabase("server=; database=; uid=; pwd="));

            const string PoolId   = "";
            const string ClientId = "";

            var provider        = new AmazonCognitoIdentityProviderClient("", "", RegionEndpoint.APSoutheast1);
            var cognitoUserPool = new CognitoUserPool(PoolId, ClientId, provider);

            services.AddSingleton <IAmazonCognitoIdentityProvider>(provider);
            services.AddSingleton(cognitoUserPool);
            services.AddCognitoIdentity();

            services.AddControllersWithViews();
            services.AddRazorPages();
        }
 public ForgotPasswordService(String userEmail)
 {
     email    = userEmail;
     provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Amazon.RegionEndpoint.CACentral1);
     userPool = new CognitoUserPool(Settings.AWS_COGNITO_POOL_ID, Settings.AWS_CLIENT_ID, provider);
     user     = new CognitoUser(email, Settings.AWS_CLIENT_ID, userPool, provider);
 }