public async void GetS3BucketsAsync() { var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials()); CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider); CognitoUser user = new CognitoUser("username", "clientID", userPool, provider); string password = "******"; AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = password }).ConfigureAwait(false); CognitoAWSCredentials credentials = user.GetCognitoAWSCredentials("identityPoolID", RegionEndpoint.< YourIdentityPoolRegion >); using (var client = new AmazonS3Client(credentials)) { ListBucketsResponse response = await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false); foreach (S3Bucket bucket in response.Buckets) { Console.WriteLine(bucket.BucketName); } } }
public static CognitoUser ValidateUser(string username) { var provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials()); var userPool = new CognitoUserPool(PoolId, ClientAppId, provider, ClientSecret); var user = new CognitoUser(username, ClientAppId, userPool, provider, ClientSecret); var initiateAuthRequest = new InitiateCustomAuthRequest { AuthParameters = new Dictionary <string, string>(StringComparer.Ordinal) { { CognitoConstants.ChlgParamUsername, username } }, ClientMetadata = new Dictionary <string, string>() }; if (!string.IsNullOrEmpty(ClientSecret)) { initiateAuthRequest.AuthParameters.Add(CognitoConstants.ChlgParamSecretHash, Util.GetUserPoolSecretHash(username, ClientAppId, ClientSecret)); } AuthFlowResponse authResponse = user.StartWithCustomAuthAsync(initiateAuthRequest).ConfigureAwait(false) .GetAwaiter().GetResult(); return(authResponse.AuthenticationResult != null ? user : null); }
public async Task <string> LoginAsync(string username, string password) { CognitoUserPool userPool = new CognitoUserPool(this.POOL_ID, this.CLIENTAPP_ID, provider); Amazon.Extensions.CognitoAuthentication.CognitoUser user = new Amazon.Extensions.CognitoAuthentication.CognitoUser(username, this.CLIENTAPP_ID, userPool, provider); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = password }; AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); if (authResponse.AuthenticationResult != null) { return(authResponse.AuthenticationResult.RefreshToken); } //var authReq = new AdminInitiateAuthRequest //{ // UserPoolId = POOL_ID, // ClientId = CLIENTAPP_ID, // AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH //}; //authReq.AuthParameters.Add("USERNAME", userName.ToLower()); //authReq.AuthParameters.Add("PASSWORD", password); //AdminInitiateAuthResponse authResp = await provider.AdminInitiateAuthAsync(authReq); return(authResponse.AuthenticationResult.IdToken); }
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; } }
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); }
public async Task <IActionResult> SignIn(SignInRequest request) { logger.LogInformation("sign in request received"); try { AuthFlowResponse authResponse = await cognitoService.SignIn(request.UserId, request.Password); return(Ok(new ApiOkResponse <SignInResponse>(new SignInResponse() { SessionId = authResponse.SessionID, AccessToken = authResponse.AuthenticationResult.AccessToken, IdToken = authResponse.AuthenticationResult.IdToken, RefreshToken = authResponse.AuthenticationResult.RefreshToken, TokenType = authResponse.AuthenticationResult.TokenType, ExpiresIn = authResponse.AuthenticationResult.ExpiresIn }))); } catch (NotAuthorizedException e) { logger.LogWarning(e, "user {UserId} failed to authenticate with cognito", request.UserId); return(Unauthorized(new ApiResponse(401, "authentication failed"))); } catch (Exception e) { logger.LogError(e, $"Unexpected exception from user {request.UserId} failing to authnticate with cognito"); throw; } }
//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); }
public virtual async Task <AuthEventEnum> VerifyNewPasswordAsync(string newPassword) { if (CurrentChallenge != AuthChallengeEnum.NewPassword) { return(AuthEventEnum.Alert_VerifyCalledButNoChallengeFound); } if (!CheckNewPasswordFormat(newPassword)) { return(AuthEventEnum.Alert_PasswordFormatRequirementsFailed); } try { switch (CurrentAuthProcess) { case AuthProcessEnum.SigningUp: authFlowResponse = await CognitoUser.RespondToNewPasswordRequiredAsync( new RespondToNewPasswordRequiredRequest() { SessionID = authFlowResponse.SessionID, NewPassword = newPassword } ).ConfigureAwait(false); this.newPassword = newPassword; AuthChallengeList.Remove(AuthChallengeEnum.NewPassword); return(await NextChallenge()); case AuthProcessEnum.ResettingPassword: this.newPassword = newPassword; CognitoUser user = new CognitoUser(login, clientId, userPool, providerClient); await user.ForgotPasswordAsync().ConfigureAwait(false); AuthChallengeList.Remove(AuthChallengeEnum.NewPassword); AuthChallengeList.Add(AuthChallengeEnum.Code); return(await NextChallenge()); case AuthProcessEnum.UpdatingPassword: this.newPassword = newPassword; AuthChallengeList.Remove(AuthChallengeEnum.NewPassword); return(await NextChallenge()); default: return(AuthEventEnum.Alert_InternalProcessError); } } catch (InvalidPasswordException) { return(AuthEventEnum.Alert_PasswordFormatRequirementsFailed); } catch (TooManyRequestsException) { return(AuthEventEnum.Alert_TooManyAttempts); } catch (TooManyFailedAttemptsException) { return(AuthEventEnum.Alert_TooManyAttempts); } catch (NotAuthorizedException) { return(AuthEventEnum.Alert_NotAuthorized); } catch (UserNotFoundException) { return(AuthEventEnum.Alert_UserNotFound); } catch (UserNotConfirmedException) { return(AuthEventEnum.Alert_NotConfirmed); } catch (Exception e) { Debug.WriteLine($"VerifyPassword() threw an exception {e}"); CognitoUser = null; return(AuthEventEnum.Alert_Unknown); } }
public async Task <SignInContext> SignIn(string userName, string password) { try { var credentials = new AnonymousAWSCredentials(); using (var client = new AmazonCognitoIdentityProviderClient(credentials, ClientHttpConfig)) { CognitoUserPool userPool = new CognitoUserPool(PoolId, ClientId, client); CognitoUser user = new CognitoUser(userName, ClientId, userPool, client); AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = password }).ConfigureAwait(false); // TODO handle other challenges if (context.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) { return new SignInContext(CognitoResult.PasswordChangeRequred) { //User = user, SessionId = context.SessionID } } ; else { return(new SignInContext(CognitoResult.Ok) { //User = user, IdToken = context.AuthenticationResult?.IdToken, RefreshToken = context.AuthenticationResult?.RefreshToken, AccessToken = context.AuthenticationResult?.AccessToken, TokenIssued = user.SessionTokens.IssuedTime, Expires = user.SessionTokens.ExpirationTime, SessionId = context.SessionID }); } } } catch (NotAuthorizedException) { return(new SignInContext(CognitoResult.NotAuthorized)); } catch (UserNotFoundException) { return(new SignInContext(CognitoResult.UserNotFound)); } catch (UserNotConfirmedException) { return(new SignInContext(CognitoResult.NotConfirmed)); } catch (Exception e) { Console.WriteLine($"SignIn() threw an exception {e}"); } return(new SignInContext(CognitoResult.Unknown)); }
public static async Task SignIn(string username, string password, bool isShowError) { AmazonCognitoIdentityProviderClient providerClient = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials() , region); CognitoUserPool userPool = new CognitoUserPool(poolId, appClientId, providerClient); CognitoUser cognitoUser = new CognitoUser(username, appClientId, userPool, providerClient); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = password }; try { AuthFlowResponse authFlow = await cognitoUser.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); isSignedIn = true; Username = cognitoUser.Username.ToString(); } catch (Exception e) { if (isShowError) { MessageBox.Show(e.Message); } return; } }
/// <summary>Update myUser SessionTokens with RefreshToken</summary> /// <param name="_RefreshToken">The CognitoUser Session RefreshToken, used to get New IdToken and AccessToken</param> /// UPDATED 13/06/2020 public async Task GetNewValidTokensAsync(string _RefreshToken) { // The "Refresh token expiration (days)" (Cognito->UserPool->General Settings->App clients->Show Details) is the // amount of time since the last login that you can use the refresh token to get new tokens. // After that period the refresh will fail // Using DateTime.Now.AddHours(1) is a workaround for https://github.com/aws/aws-sdk-net-extensions-cognito/issues/24 myUser.SessionTokens = new CognitoUserSession(myUser.SessionTokens.IdToken, myUser.SessionTokens.AccessToken, _RefreshToken, DateTime.Now, DateTime.Now.AddHours(1)); try { AuthFlowResponse context = await myUser.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest { AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH }) .ConfigureAwait(false); myUser.SessionTokens.RefreshToken = _RefreshToken; // Problem is StartWithRefreshTokenAuthAsync return a Null RefreshToken so i will keep my current One. currentUserSession = new UserSession(myUser.SessionTokens.AccessToken, myUser.SessionTokens.IdToken, _RefreshToken); ServerSend.SendTokens(id, currentUserSession); } catch (NotAuthorizedException) { //https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html // refresh tokens will expire - user must login manually every x days (see user pool -> app clients -> details) Console.WriteLine("Ask to Client to Login Manually"); //return new SignInContext(CognitoResult.RefreshNotAuthorized) { ResultMessage = ne.Message }; } catch (Exception e) { NlogClass.target.WriteAsyncLogEvent(new AsyncLogEventInfo(new LogEventInfo(LogLevel.Error, "GetNewValidTokensAsync", "Client Name : " + myUser.Username + " | RefreshToken Create New Session failed | Exception : " + e), NlogClass.exceptions.Add)); } }
private async Task <bool> Authorize(string password) { if (password != null) { try { AuthFlowResponse AuthResponse = await User.StartWithSrpAuthAsync (new InitiateSrpAuthRequest() { Password = password }).ConfigureAwait(false); if (AuthResponse != null) { Debug.Log("User successfully authenticated"); Client.DefaultRequestHeaders.Accept.Clear(); Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(User.SessionTokens.IdToken); Debug.Log(User.SessionTokens.IdToken); return(true); } } catch (NotAuthorizedException e) { Debug.Log("Authentication Error"); Debug.Log(e); return(false); } } return(false); }
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 static User FromCode(string scode) { WebRequest req = WebRequest.Create($"https://accounts.spotify.com/api/token"); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; StreamWriter stream = new StreamWriter(req.GetRequestStream()); stream.Write($"grant_type=authorization_code&code={scode}&redirect_uri={redirect}&client_id={SpotifyAuthKeys.client_id}&client_secret={SpotifyAuthKeys.client_secret}"); stream.Flush(); stream.Close(); try { WebResponse res = req.GetResponse(); StreamReader reader = new StreamReader(res.GetResponseStream()); JToken data = JToken.Parse(reader.ReadToEnd()); AuthFlowResponse flowResponse = data.ToObject <AuthFlowResponse>(); return(new User(flowResponse.access_token, flowResponse.refresh_token, DateTime.Now.AddSeconds(int.Parse(flowResponse.expires_in)).AddMinutes(-1))); } catch (WebException e) { Console.WriteLine(e.ToString()); } return(null); }
internal async Task <CognitoUser> ValidateUser(string username, string password) { AmazonCognitoIdentityProviderClient providerClient = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), REGION); CognitoUserPool userPool = new CognitoUserPool(USERPOOL_ID, CLIENT_ID, providerClient); CognitoUser user = new CognitoUser(username, CLIENT_ID, userPool, providerClient); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = password }; AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(true); while (authResponse.AuthenticationResult == null) { if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) { authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest() { NewPassword = password, SessionID = authResponse.SessionID }).ConfigureAwait(true); } } if (authResponse.AuthenticationResult != null) { return(user); } else { return(null); } }
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); }
public async Task <AuthFlowResponse> StartWithSrpAuthAsync(string userId, string password) { var provider = new AmazonCognitoIdentityProviderClient(null, this.RegionEndpoint); CognitoUserPool userPool = new CognitoUserPool( UserPoolId, ClientId, provider, ClientSecret ); CognitoUser user = new CognitoUser( userId, ClientId, userPool, provider, ClientSecret ); try { AuthFlowResponse response = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = password }).ConfigureAwait(false); return(response); } catch (Exception ex) { throw; } }
public async void Test_GivenAUserWithNo2FA_WhenPasswordSignIn_ThenReturnSigninResultSuccess() { var cognitoUser = GetCognitoUser(); var authFlowResponse = new AuthFlowResponse("sessionId", null, null, null, null); bool isPasswordChangeRequired = false; var signinResult = SignInResult.Success; userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny <string>())).Returns(Task.FromResult(cognitoUser)).Verifiable(); userManagerMock.Setup(mock => mock.IsPasswordChangeRequiredAsync(It.IsAny <CognitoUser>())).Returns(Task.FromResult(isPasswordChangeRequired)).Verifiable(); userManagerMock.Setup(mock => mock.CheckPasswordAsync(It.IsAny <CognitoUser>(), It.IsAny <string>())) .Returns(Task.FromResult(authFlowResponse)) .Callback(() => cognitoUser.SessionTokens = new CognitoUserSession("idToken", "accessToken", "refreshToken", DateTime.Now, DateTime.Now.AddDays(1))).Verifiable(); userManagerMock.Setup(mock => mock.GetClaimsAsync(It.IsAny <CognitoUser>())).Returns(Task.FromResult(new List <Claim>() as IList <Claim>)).Verifiable(); userManagerMock.Setup(mock => mock.GetRolesAsync(It.IsAny <CognitoUser>())).Returns(Task.FromResult(new List <string>() as IList <string>)).Verifiable(); var context = MockUtils.MockContext(cognitoUser, IdentityConstants.TwoFactorUserIdScheme); contextAccessorMock.Setup(a => a.HttpContext).Returns(context).Verifiable(); var output = await signinManager.PasswordSignInAsync("userId", "password", true, false).ConfigureAwait(false); Assert.Equal(signinResult, output); userManagerMock.Verify(); contextAccessorMock.Verify(); }
public static async Task <string> SignIn(string username, string password) { try { CognitoUserPool userPool = new CognitoUserPool(AWS.UserPoolId, AWS.ClientId, App.provider); CognitoUser user = new CognitoUser(username, AWS.ClientId, userPool, App.provider); AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = password }).ConfigureAwait(false); if (context.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) { return("User must change password."); } else { App.user = new AWSUser { IdToken = context.AuthenticationResult?.IdToken, RefreshToken = context.AuthenticationResult?.RefreshToken, AccessToken = context.AuthenticationResult?.AccessToken, TokenIssued = user.SessionTokens.IssuedTime, Expires = user.SessionTokens.ExpirationTime }; return("User logged in."); } } catch (Exception err) { return("Error: " + err.Message); } }
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); } }
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; } }
public static void Refresh(User user) { WebRequest req = WebRequest.Create($"https://accounts.spotify.com/api/token"); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; StreamWriter stream = new StreamWriter(req.GetRequestStream()); stream.Write($"grant_type=refresh_token&refresh_token={user.refreshtoken}&client_id={SpotifyAuthKeys.client_id}&client_secret={SpotifyAuthKeys.client_secret}"); stream.Flush(); stream.Close(); try { WebResponse res = req.GetResponse(); StreamReader reader = new StreamReader(res.GetResponseStream()); JToken data = JToken.Parse(reader.ReadToEnd()); AuthFlowResponse flowResponse = data.ToObject <AuthFlowResponse>(); user.authtoken = flowResponse.access_token; user.authExpires = DateTime.Now.AddSeconds(int.Parse(flowResponse.expires_in)).AddMinutes(-1); } catch (WebException e) { Console.WriteLine(e.ToString()); } }
//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; } }
public static async void GetCredsChallengesAsync() { AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials()); CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider); CognitoUser user = new CognitoUser("username", "clientID", userPool, provider); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = "******" }; AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); while (authResponse.AuthenticationResult == null) { if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) { Console.WriteLine("Enter your desired new password:"******"Enter the MFA Code sent to your device:"); string mfaCode = Console.ReadLine(); AuthFlowResponse mfaResponse = await user.RespondToSmsMfaAuthAsync(new RespondToSmsMfaRequest() { SessionID = authResponse.SessionID, MfaCode = mfaCode }).ConfigureAwait(false); accessToken = authResponse.AuthenticationResult.AccessToken; } else { Console.WriteLine("Unrecognized authentication challenge."); accessToken = ""; break; } } if (authResponse.AuthenticationResult != null) { Console.WriteLine("User successfully authenticated."); } else { Console.WriteLine("Error in authentication process."); } }
public LoginUserQueryParam ChangePassword(ResetPasswordQueryParams changePasswordParams) { var userPool = new CognitoUserPool(_connectionInfo.UserPoolId, _connectionInfo.ClientId, _provider); var cognitoUser = new CognitoUser(changePasswordParams.Email, _connectionInfo.ClientId, userPool, _provider); try { AuthFlowResponse authResponse = null; authResponse = cognitoUser.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = changePasswordParams.Password }).Result; while (authResponse.AuthenticationResult == null) { if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) { authResponse = cognitoUser.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest() { SessionID = authResponse.SessionID, NewPassword = changePasswordParams.NewPassword, }).Result; } } if (authResponse.AuthenticationResult != null) { LoggingHandler.LogInfo("User successfully authenticated."); var loginParams = new LoginUserQueryParam(); loginParams.Email = changePasswordParams.Email; loginParams.Password = changePasswordParams.NewPassword; return(loginParams); } else { LoggingHandler.LogError("Error in authentication process."); } } catch (AggregateException e) { e.Handle((x) => { if (x is NotAuthorizedException) // This we know how to handle. { LoggingHandler.LogInfo("Authentication Gateway: Invalid credentials provided."); return(true); } if (x is UserNotFoundException) // This we know how to handle. { LoggingHandler.LogInfo("Authentication Gateway: User not found."); return(true); } return(false); // Let anything else stop the application. }); } return(null); }
public virtual void InternalClearAsync() { ClearSensitiveFields(); CognitoUser = null; AuthChallengeList.Clear(); authFlowResponse = null; IsSignedIn = false; CurrentAuthProcess = AuthProcessEnum.None; }
public async Task TestValidSession() { AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = "******" }).ConfigureAwait(false); Assert.True(user.SessionTokens.IsValid()); }
public async void Test_GivenAUser_WhenCheckPassword_ThenResponseIsNotAltered() { var authFlowResponse = new AuthFlowResponse("sessionId", null, null, null, null); userStoreMock.Setup(mock => mock.StartValidatePasswordAsync(It.IsAny <CognitoUser>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(authFlowResponse)).Verifiable(); var output = await userManager.CheckPasswordAsync(GetCognitoUser(), "password").ConfigureAwait(false); Assert.Equal(authFlowResponse, output); userStoreMock.Verify(); }
public async void Test_GivenAUser_WhenRespondToTwoFactorChallenge_ThenResponseIsNotAltered() { var authFlowResponse = new AuthFlowResponse("sessionId", null, ChallengeNameType.SMS_MFA, null, null); userStoreMock.Setup(mock => mock.RespondToTwoFactorChallengeAsync(It.IsAny <CognitoUser>(), It.IsAny <string>(), It.IsAny <ChallengeNameType>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(authFlowResponse)).Verifiable(); var output = await userManager.RespondToTwoFactorChallengeAsync(GetCognitoUser(), "2FACODE", "SessionId").ConfigureAwait(false); Assert.Equal(authFlowResponse, output); userStoreMock.Verify(); }
public async Task <ResultadoAutenticacaoDTO> Autenticar(AutenticacaoDTO autenticacao) { ResultadoAutenticacaoDTO resultado = new ResultadoAutenticacaoDTO(); if (autenticacao == null || string.IsNullOrEmpty(autenticacao.Usuario) || string.IsNullOrEmpty(autenticacao.Senha)) { resultado.Status = EnumResultadoAutenticacao.FALHA_CREDENCIAIS; } else { try { using (AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient( new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.GetBySystemName(this._awsConfigAdapter.Cognito.PoolRegion))) { CognitoUserPool userPool = new CognitoUserPool( this._awsConfigAdapter.Cognito.PoolID, this._awsConfigAdapter.Cognito.ClientID, provider, this._awsConfigAdapter.Cognito.ClientSecret); CognitoUser user = new CognitoUser( autenticacao.Usuario, this._awsConfigAdapter.Cognito.ClientID, userPool, provider, this._awsConfigAdapter.Cognito.ClientSecret); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = autenticacao.Senha }; AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest); resultado.Status = EnumResultadoAutenticacao.SUCESSO; resultado.Token = authResponse.AuthenticationResult.IdToken; } } catch (Amazon.CognitoIdentityProvider.Model.NotAuthorizedException naEx) { this._logger.LogError(naEx, "Tentativa de login bloqueada. Usuario: {0} / Senha: {1}", autenticacao.Usuario, autenticacao.Senha); resultado.Status = EnumResultadoAutenticacao.FALHA_CREDENCIAIS; } catch (Exception ex) { this._logger.LogError(ex, "Erro no processo de autenticaĆ§Ć£o"); resultado.Status = EnumResultadoAutenticacao.ERRO_NAO_TRATADO; } } return(resultado); }