Example #1
0
    public static BooleanResult getResponse(String userName, String password)
    {
        try
        {
            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);

            return(new BooleanResult()
            {
                Success = true
            });
        }
        catch
        {
            return(new BooleanResult()
            {
                Success = false
            });
        }
    }
        public async Task <ActionResult <string> > SignIn(User user)
        {
            var cognito = new AmazonCognitoIdentityProviderClient(_region);

            try
            {
                var request = new AdminInitiateAuthRequest
                {
                    UserPoolId = "us-east-1_h2hBTYgfp",
                    ClientId   = _clientId,
                    AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
                };

                request.AuthParameters.Add("USERNAME", user.Username);
                request.AuthParameters.Add("PASSWORD", user.Password);

                var response = await cognito.AdminInitiateAuthAsync(request);

                return(Ok(response.AuthenticationResult.IdToken));
            }
            catch (UserNotFoundException)
            {
                return(BadRequest("Username or password is invalid"));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
        public async Task <ActionResult <string> > SignIn(User user)
        {
            var cognito = new AmazonCognitoIdentityProviderClient(_region);

            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = "us-west-2_EOGDtXwex",
                ClientId   = _clientId,
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
            };

            request.AuthParameters.Add("USERNAME", user.Username);
            request.AuthParameters.Add("PASSWORD", user.Password);

            try
            {
                var response = await cognito.AdminInitiateAuthAsync(request);

                return(Ok(response.AuthenticationResult.IdToken));
            }
            catch (Exception ex)
            {
                return(Ok(ex));
            }
        }
        /// <summary>
        /// The resulting refresh token will be null and cognito expects the current refresh token to
        /// be utilized until it expires. When it expires, user needs to be authenticated
        /// https://github.com/aws/aws-aspnet-cognito-identity-provider/issues/76
        /// </summary>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public async Task <string> GetRenewedTokenAsync(string refreshToken)
        {
            var authParam = new Dictionary <string, string>();

            authParam.Add("REFRESH_TOKEN", refreshToken);
            var req = new AdminInitiateAuthRequest()
            {
                AuthParameters = authParam,
                UserPoolId     = _userPool.PoolID,
                AuthFlow       = AuthFlowType.REFRESH_TOKEN,
                ClientId       = _userPool.ClientID
            };

            try
            {
                var result = await _provider.AdminInitiateAuthAsync(req);

                var idToken = result.AuthenticationResult.IdToken;
                return(idToken);
            }
            catch (NotAuthorizedException)
            {
                throw new CcsSsoException("INVALID_REFRESH_TOKEN");
            }
        }
Example #5
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;
            }
        }
        public async Task <IActionResult> SignIn(User user)
        {
            if (!ModelState.IsValid)
            {
                return(ResponseMessageHelper.ModelStateInvalid(ModelState));
            }

            var cognito = new AmazonCognitoIdentityProviderClient(_region);

            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = _config.Value.AwsCognitoUserPoolId,
                ClientId   = _config.Value.AwsCognitoAppClientId,
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
            };

            request.AuthParameters.Add("USERNAME", user.Username);
            request.AuthParameters.Add("PASSWORD", user.Password);

            try
            {
                var response = await cognito.AdminInitiateAuthAsync(request);

                return(ResponseMessageHelper.Ok(response.AuthenticationResult.IdToken));
            }
            catch (NotAuthorizedException ex)
            {
                return(ResponseMessageHelper.Unauthorized(ex.Message));
            }
            catch (Exception ex)
            {
                return(ResponseMessageHelper.InternalServerError(ex.Message));
            }
        }
Example #7
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);
            }
        }
        public async Task <bool> CheckPasswordAsync(string userName, string password)
        {
            var userName1 = "*****@*****.**";
            var passwrod1 = "MytestPass141!asdfasdf";

            try
            {
                var authReq = new AdminInitiateAuthRequest
                {
                    UserPoolId = "us-east-1_0lir0CGDl",
                    ClientId   = "6aaambb1i02abdkokr2n4ohojl",
                    AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
                };
                authReq.AuthParameters.Add("USERNAME", userName);
                authReq.AuthParameters.Add("PASSWORD", password);

                AdminInitiateAuthResponse authResp = await _client.AdminInitiateAuthAsync(authReq);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #9
0
        /// <summary>
        /// Initiates the asynchronous ADMIN_NO_SRP_AUTH authentication flow
        /// </summary>
        /// <param name="adminAuthRequest">InitiateAdminNoSrpAuthRequest object containing the necessary
        /// parameters to initiate the ADMIN_NO_SRP_AUTH authentication flow</param>
        /// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
        /// if one exists</returns>
        public void StartWithAdminNoSrpAuthAsync(InitiateAdminNoSrpAuthRequest adminAuthRequest, AsyncCallback <AuthFlowResponse> callback = null)
        {
            AdminInitiateAuthRequest initiateAuthRequest = CreateAdminAuthRequest(adminAuthRequest);

            Provider.AdminInitiateAuthAsync(initiateAuthRequest, r =>
            {
                if (r.Exception != null)
                {
                    callback?.Invoke(new AsyncResult <AuthFlowResponse>(null, r.Exception));
                    return;
                }

                AdminInitiateAuthResponse initiateResponse = r.Response;
                UpdateSessionIfAuthenticationComplete(initiateResponse.ChallengeName, initiateResponse.AuthenticationResult);

                callback?.Invoke(new AsyncResult <AuthFlowResponse>(new AuthFlowResponse()
                {
                    SessionID            = initiateResponse.Session,
                    ChallengeName        = initiateResponse.ChallengeName,
                    AuthenticationResult = initiateResponse.AuthenticationResult,
                    ChallengeParameters  = initiateResponse.ChallengeParameters,
                    ClientMetadata       = new Dictionary <string, string>(initiateResponse.ResponseMetadata.Metadata)
                }, null));
            });
        }
        public async Task <AuthResponse> LogIn(string username, string password)
        {
            try
            {
                var authReq = new AdminInitiateAuthRequest
                {
                    UserPoolId = Config.UserPoolId,
                    ClientId   = Config.ClientId,
                    AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH,
                };
                authReq.AuthParameters.Add("USERNAME", username);
                authReq.AuthParameters.Add("PASSWORD", password);
                //authReq.AuthParameters.Add("SECRET_HASH", AuthHelper.HashHmac(Config.UserPoolId, Config.ClientSecret));

                AdminInitiateAuthResponse authResp = await _client.AdminInitiateAuthAsync(authReq);

                return(new AuthResponse
                {
                    AccessToken = authResp.AuthenticationResult.AccessToken,
                    ExpiresIn = authResp.AuthenticationResult.ExpiresIn,
                    IdToken = authResp.AuthenticationResult.IdToken,
                    RefreshToken = authResp.AuthenticationResult.RefreshToken,
                    TokenType = authResp.AuthenticationResult.TokenType,
                });
            }
            catch (Exception ex)
            {
                return(new AuthResponse
                {
                    ErrorMessage = ex.Message
                });
            }
        }
Example #11
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();
        }
Example #12
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);
        }
Example #13
0
        public async Task <ActionResult <string> > SignIn(User user)
        {
            RegionEndpoint region  = RegionEndpoint.GetBySystemName(this.cognitoSettings.Value.Region);
            var            cognito = new AmazonCognitoIdentityProviderClient(region);

            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = this.cognitoSettings.Value.PoolId,
                ClientId   = this.cognitoSettings.Value.AppClientId,
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
            };

            request.AuthParameters.Add("USERNAME", user.Username);
            request.AuthParameters.Add("PASSWORD", user.Password);

            var response = await cognito.AdminInitiateAuthAsync(request);

            var expireDate = DateTime.Now.AddSeconds(response.AuthenticationResult.ExpiresIn);

            return(Ok(new
            {
                id_token = response.AuthenticationResult.IdToken,
                expires_at = expireDate,
                username = user.Username
            }));
        }
        private AdminInitiateAuthRequest CreateAdminAuthRequest(InitiateAdminNoSrpAuthRequest adminRequest)
        {
            AdminInitiateAuthRequest returnRequest = new AdminInitiateAuthRequest()
            {
                AuthFlow       = AuthFlowType.ADMIN_NO_SRP_AUTH,
                ClientId       = ClientID,
                UserPoolId     = UserPool.PoolID,
                AuthParameters = new Dictionary <string, string>()
                {
                    { CognitoConstants.ChlgParamUsername, Username },
                    { CognitoConstants.ChlgParamPassword, adminRequest.Password }
                }
            };

            if (Device != null && !string.IsNullOrEmpty(Device.DeviceKey))
            {
                returnRequest.AuthParameters.Add(CognitoConstants.ChlgParamDeviceKey, Device.DeviceKey);
            }

            if (!string.IsNullOrEmpty(SecretHash))
            {
                returnRequest.AuthParameters.Add(CognitoConstants.ChlgParamSecretHash, SecretHash);
            }

            if (adminRequest.ClientMetadata != null)
            {
                returnRequest.ClientMetadata = new Dictionary <string, string>(adminRequest.ClientMetadata);
            }

            return(returnRequest);
        }
Example #15
0
        public async Task <ActionResult <string> > GetAsync(TokenCredential credential)
        {
            var request = new AdminInitiateAuthRequest
            {
                ClientId   = _options.UserPoolClientId,
                UserPoolId = _options.UserPoolId,
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH,
            };

            // For ADMIN_NO_SRP_AUTH: USERNAME (required), SECRET_HASH (if app client is configured
            // with client secret), PASSWORD (required)
            request.AuthParameters.Add("USERNAME", credential.Email);
            request.AuthParameters.Add("PASSWORD", credential.Password);
            request.AuthParameters.Add("SECRET_HASH", _clientSecret.ComputeHash(credential.Email));

            string accessToken = string.Empty;

            try
            {
                var response = await _identityProvider.AdminInitiateAuthAsync(request);

                accessToken = response.AuthenticationResult.AccessToken;
            }
            catch (UserNotFoundException)
            {
                ModelState.AddModelError("UserNotFound", $"A user having email '{credential.Email}' does not exist.");
                return(BadRequest(ModelState));
            }

            return(accessToken);
        }
        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);
            }
        }
        private async Task <bool> CheckPasswordAsync(string userName, string password)
        {
            try
            {
                var authReq = new AdminInitiateAuthRequest()
                {
                    UserPoolId = _poolId,
                    ClientId   = _clientId,
                    AuthFlow   = AuthFlowType.ADMIN_USER_PASSWORD_AUTH,
                };
                authReq.AuthParameters.Add("USERNAME", userName);
                authReq.AuthParameters.Add("PASSWORD", password);

                AdminInitiateAuthResponse authResp = await _client.AdminInitiateAuthAsync(authReq);

                // await new MessageDialog(authResp.ToString(), "Sign In Result").ShowAsync();
                return(true);
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                await new MessageDialog(message, "Sign In Error").ShowAsync();
                return(false);
            }
        }
Example #18
0
        public async Task <ActionResult <InitiateAuthResponse> > Signin([FromBody] AdminInitiateAuthRequest request)
        {
            request.AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH;
            var result = await this.client.AdminInitiateAuthAsync(request).ConfigureAwait(false);

            this.logger.LogInformation("Successful cognito request");
            return(new OkObjectResult(result));
        }
Example #19
0
        public async Task <string> GetIdFromRefresh(string refreshToken)
        {
            var authReq = new AdminInitiateAuthRequest
            {
                UserPoolId = userPoolId,
                ClientId   = clientId,
                AuthFlow   = AuthFlowType.REFRESH_TOKEN_AUTH
            };

            AdminInitiateAuthResponse authResp = await new AmazonCognitoIdentityProviderClient().AdminInitiateAuthAsync(authReq);

            return(authResp.AuthenticationResult.IdToken);
        }
Example #20
0
        /// <summary>
        /// Password flow, using admin API to fetch user details
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns> CognitoUserCustomAttributes </returns>
        private async Task <CognitoUserCustomAttributes> AuthenticateAndGetCognitoUserCustomAttributes(string userName, string password)
        {
            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = userPoolId,
                ClientId   = clientId,
                AuthFlow   = AuthFlowType.ADMIN_USER_PASSWORD_AUTH
            };

            request.AuthParameters.Add("USERNAME", userName);
            request.AuthParameters.Add("PASSWORD", password);

            AdminInitiateAuthResponse response;

            try
            {
                response = await cognitoClient.AdminInitiateAuthAsync(request);
            }
            catch (Exception ex)
            {
                return(new CognitoUserCustomAttributes
                {
                    ErrorMessage = ex.Message
                });
            }

            if (response.HttpStatusCode != HttpStatusCode.OK)
            {
                return(new CognitoUserCustomAttributes
                {
                    ErrorMessage = "Login error"
                });
            }

            var hand             = new JwtSecurityTokenHandler();
            var customAttributes = hand.ReadJwtToken(response.AuthenticationResult.IdToken);

            var identityResponse = new CognitoUserCustomAttributes
            {
                Role = GetCustomAttributeValue(customAttributes, CustomAttributeField.Role),
                HomeDirectoryDetails = GetCustomAttributeValue(customAttributes, CustomAttributeField.HomeDirectoryDetails),
                HomeDirectory        = GetCustomAttributeValue(customAttributes, CustomAttributeField.HomeDirectory),
                Policy = GetCustomAttributeValue(customAttributes, CustomAttributeField.Policy)
            };

            // HomeDirectoryDetails to hide actual S3 path
            identityResponse.HomeDirectoryType = identityResponse.HomeDirectoryDetails != null ? CustomAttributeField.HomeDirectoryType : null;

            return(identityResponse);
        }
Example #21
0
        private AdminInitiateAuthRequest GetAuthRequest(string username, string password)
        {
            AdminInitiateAuthRequest request = new AdminInitiateAuthRequest
            {
                UserPoolId = GetUserPoolId(),
                ClientId   = GetClientId(),
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
            };

            request.AuthParameters.Add(AuthenticationParameters.USERNAME, username);
            request.AuthParameters.Add(AuthenticationParameters.PASSWORD, password);

            return(request);
        }
        /// <summary>
        /// Initiates the asynchronous ADMIN_NO_SRP_AUTH authentication flow
        /// </summary>
        /// <param name="adminAuthRequest">InitiateAdminNoSrpAuthRequest object containing the necessary
        /// parameters to initiate the ADMIN_NO_SRP_AUTH authentication flow</param>
        /// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
        /// if one exists</returns>
        public async Task <AuthFlowResponse> StartWithAdminNoSrpAuthAsync(InitiateAdminNoSrpAuthRequest adminAuthRequest)
        {
            AdminInitiateAuthRequest initiateAuthRequest = CreateAdminAuthRequest(adminAuthRequest);

            AdminInitiateAuthResponse initiateResponse =
                await Provider.AdminInitiateAuthAsync(initiateAuthRequest).ConfigureAwait(false);

            UpdateSessionIfAuthenticationComplete(initiateResponse.ChallengeName, initiateResponse.AuthenticationResult);

            return(new AuthFlowResponse(initiateResponse.Session,
                                        initiateResponse.AuthenticationResult,
                                        initiateResponse.ChallengeName,
                                        initiateResponse.ChallengeParameters,
                                        new Dictionary <string, string>(initiateResponse.ResponseMetadata.Metadata)));
        }
        public async Task <ActionResult <string> > SignIn([FromQuery, Required] string username, [FromQuery, Required] string password)
        {
            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = UserPoolId,
                ClientId   = ClientId,
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
            };

            request.AuthParameters.Add("USERNAME", username);
            request.AuthParameters.Add("PASSWORD", password);

            var response = await _client.AdminInitiateAuthAsync(request);

            return(Ok(response.AuthenticationResult.IdToken));
        }
Example #24
0
        public override async Task Start(string _postJson, IDynamoDBContext _dynamoDBContext)
        {
            await base.Start(_postJson, _dynamoDBContext);

            User user = JsonConvert.DeserializeObject <User>(_postJson);


            var authReq = new AdminInitiateAuthRequest()
            {
                UserPoolId = ApiDefine.CognitoPoolId,
                ClientId   = ApiDefine.CognitoClientId,
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
            };

            authReq.AuthParameters.Add("USERNAME", user.Email);
            authReq.AuthParameters.Add("EMAIL", user.Email);
            authReq.AuthParameters.Add("PASSWORD", user.Password);

            var client = new AmazonCognitoIdentityProviderClient(ApiDefine.Credentials, RegionEndpoint.USWest2);
            AdminInitiateAuthResponse authResp = await client.AdminInitiateAuthAsync(authReq);

            // AccessTokenを元にUser名を取得
            var getUserReq = new GetUserRequest()
            {
                AccessToken = authResp.AuthenticationResult.AccessToken
            };

            var getUserResp = await client.GetUserAsync(getUserReq);

            /*var req = new AdminRespondToAuthChallengeRequest()
             * {
             *  ChallengeName = ChallengeNameType.ADMIN_NO_SRP_AUTH,
             *  ClientId = ApiDefine.CognitoClientId,
             *  UserPoolId = ApiDefine.CognitoPoolId,
             *  Session = authResp.Session,
             *  ChallengeResponses = new Dictionary<string, string>() {
             *      { "USERNAME", user.Email }, { "PASSWORD", user.Password }
             *  },
             * };
             * var resp =  await client.AdminRespondToAuthChallengeAsync(req);*/
            JsPath = "cognito/my.page.js";
            string json = JsonConvert.SerializeObject(getUserResp);

            await loadJs();

            ExecJs = ExecJs.Replace("_JSON", json.Replace("\"", "\\\""));
        }
Example #25
0
        public static async Task <AuthenticationResultType> GetToken(string userName = "******", string password = "******")
        {
            var cognito = new AmazonCognitoIdentityProviderClient(_region);
            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = UserPoolId,
                ClientId   = _clientId,
                AuthFlow   = AuthFlowType.ADMIN_USER_PASSWORD_AUTH
            };

            request.AuthParameters.Add("USERNAME", userName);
            request.AuthParameters.Add("PASSWORD", password);

            var response = await cognito.AdminInitiateAuthAsync(request);

            return(response.AuthenticationResult);
        }
Example #26
0
        public async Task <AccountLoginResponseModel> Signin(AccountLoginModel model)
        {
            var cognito = new AmazonCognitoIdentityProviderClient(_secret.AwsAccessKey, _secret.AwsSecretKey, _region);
            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = _secret.UserPoolId,
                ClientId   = _secret.ClientId,
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
            };

            request.AuthParameters.Add("USERNAME", model.Username);
            request.AuthParameters.Add("PASSWORD", model.Password);

            var response = await cognito.AdminInitiateAuthAsync(request);

            return(Mapper.Map <AccountLoginResponseModel>(response));
        }
        public async Task <ActionResult <string> > Signin([FromBody] User user)
        {
            var validation = user != default(User) &&
                             !string.IsNullOrEmpty(user.UserName) &&
                             !string.IsNullOrEmpty(user.Password);

            if (!validation)
            {
                return(BadRequest());
            }

            var token          = string.Empty;
            var clientId       = "20jo0qhegstp7ovimab8nln5pg";
            var userPoolId     = @"ap-southeast-1_TarRBIFR7";
            var awsCredentials = new BasicAWSCredentials(
                accessKey: "AKIAJLCJTGLJZ67AAAZA",
                secretKey: "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");

            try
            {
                var authenticationRequest = new AdminInitiateAuthRequest
                {
                    UserPoolId = userPoolId,
                    ClientId   = clientId,
                    AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
                };

                authenticationRequest.AuthParameters.Add("USERNAME", user.UserName);
                authenticationRequest.AuthParameters.Add("PASSWORD", user.Password);

                using (var client =
                           new AmazonCognitoIdentityProviderClient(awsCredentials, RegionEndpoint.APSouth1))
                {
                    var response = await client.AdminInitiateAuthAsync(authenticationRequest);

                    token = response.AuthenticationResult.IdToken;
                }
            }
            catch (Exception exceptionObject)
            {
                throw exceptionObject;
            }

            return(Ok(token));
        }
Example #28
0
        public async Task <AdminInitiateAuthResponse> PerformAuthAsync(UserForCreationDto user)
        {
            var authRequest = new AdminInitiateAuthRequest
            {
                UserPoolId = _settings.Value.UserPoolId,
                ClientId   = _settings.Value.UserPoolClientId,
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
            };

            authRequest.AuthParameters.Add("USERNAME", user.UserName);
            authRequest.AuthParameters.Add("PASSWORD", user.Password);

            AmazonCognitoIdentityProviderClient _client = new AmazonCognitoIdentityProviderClient();

            AdminInitiateAuthResponse authResponse = await _client.AdminInitiateAuthAsync(authRequest);

            return(authResponse);
        }
        public async Task <IActionResult> SignIn(User user)
        {
            var cognito = new AmazonCognitoIdentityProviderClient(_region);

            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = _appConfig.Value.PoolId,
                ClientId   = _appConfig.Value.AppClientId,
                AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
            };

            request.AuthParameters.Add("USERNAME", user.Username);
            request.AuthParameters.Add("PASSWORD", user.Password);

            var response = await cognito.AdminInitiateAuthAsync(request);

            return(Ok(response.AuthenticationResult.IdToken));
        }
Example #30
0
        public AdminInitiateAuthResponse Login(LoginRequestDTO request)
        {
            var authParams = new Dictionary <string, string>();

            authParams.Add("USERNAME", request.username);
            authParams.Add("PASSWORD", request.password);


            var authRequest = new AdminInitiateAuthRequest()
            {
                AuthFlow       = AuthFlowType.ADMIN_NO_SRP_AUTH,
                AuthParameters = authParams,
                ClientId       = ConfigurationManager.AppSettings["CLIENT_ID"],
                UserPoolId     = ConfigurationManager.AppSettings["USERPOOL_ID"]
            };

            return(client.AdminInitiateAuth(authRequest));
        }