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 async Task <string> GetS3BucketsAsync(CognitoUser user) { CognitoAWSCredentials credentials = user.GetCognitoAWSCredentials(FED_POOL_ID, new AppConfigAWSRegion().Region); StringBuilder bucketlist = new StringBuilder(); bucketlist.Append("================Cognito Credentails==================\n"); bucketlist.Append("Access Key - " + credentials.GetCredentials().AccessKey); bucketlist.Append("\nSecret - " + credentials.GetCredentials().SecretKey); bucketlist.Append("\nSession Token - " + credentials.GetCredentials().Token); bucketlist.Append("\n================User Buckets==================\n"); using (var client = new AmazonS3Client(credentials)) { ListBucketsResponse response = await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false); foreach (S3Bucket bucket in response.Buckets) { bucketlist.Append(bucket.BucketName); bucketlist.Append("\n"); } } Console.WriteLine(bucketlist.ToString()); return(bucketlist.ToString()); }
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); }
private void OnSignedUp(string deviceId, string devicePassword, TaskCompletionSource <ICognitoAWSCredentials> promise) { var userPool = new CognitoUserPool(_userPoolId, _clientId, _cipClient); var user = new CognitoUser(deviceId, userPool.ClientID, userPool, _cipClient); var srpRequest = new InitiateSrpAuthRequest(); srpRequest.Password = devicePassword; _logger.Log($"Authenticating for user {deviceId}"); user.StartWithSrpAuthAsync(srpRequest, srpResult => { if (srpResult.Exception != null) { if (srpResult.Exception is UserNotFoundException) { var signUpRequest = new SignUpRequest(); signUpRequest.Username = deviceId; signUpRequest.Password = devicePassword; signUpRequest.ClientId = _clientId; _logger.Log($"SignUp with new credentials for user {deviceId}"); _cipClient.SignUpAsync(signUpRequest, signUpResult => { if (signUpResult.Exception != null) { promise.SetException(signUpResult.Exception); return; } _logger.Log("SignUp success!"); if (signUpResult.Response != null) { _logger.Log("UserSub:" + signUpResult.Response.UserSub); } _preferences.SetValue(_DeviceIdKey, deviceId); _preferences.SetValue(_DevicePasswordKey, devicePassword); OnSignedUp(deviceId, devicePassword, promise); }); return; } promise.SetException(srpResult.Exception); return; } _logger.Log("Authentication success!"); ICognitoAWSCredentials credentials = user.GetCognitoAWSCredentials( _identityPoolId, RegionEndpoint.GetBySystemName(_region), _aws); promise.SetResult(credentials); }); }
static private async Task <UserCognitoCredentials> getCognitoCredentials(String userEmail, String userPassword) { String cognitoUserPoolId = "us-east-1_n8TiZp7tu"; String cognitoClientId = "6clvd0v40jggbaa5qid2h6hkqf"; String cognitoIdentityPoolId = "us-east-1:bff024bb-06d0-4b04-9e5d-eb34ed07f884"; Amazon.RegionEndpoint cognitoRegion = Amazon.RegionEndpoint.USEast1; AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Amazon.RegionEndpoint.USEast1); CognitoUserPool userPool = new CognitoUserPool(cognitoUserPoolId, cognitoClientId, provider); CognitoUser user = new CognitoUser(userEmail, cognitoClientId, userPool, provider); AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = userPassword }).ConfigureAwait(false); String accessToken = context.AuthenticationResult.AccessToken; String idToken = context.AuthenticationResult.IdToken; CognitoAWSCredentials credentials = user.GetCognitoAWSCredentials(cognitoIdentityPoolId, cognitoRegion); var identityClient = new AmazonCognitoIdentityClient(credentials, cognitoRegion); var idRequest = new Amazon.CognitoIdentity.Model.GetIdRequest(); idRequest.IdentityPoolId = cognitoIdentityPoolId; idRequest.Logins = new Dictionary <string, string> { { "cognito-idp.us-east-1.amazonaws.com/" + cognitoUserPoolId, idToken } }; var idResponseId = await identityClient.GetIdAsync(idRequest).ConfigureAwait(false); if (idResponseId.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine(String.Format("Failed to get credentials for identity. Status code: {0} ", idResponseId.HttpStatusCode)); System.Environment.Exit(1); } var idResponseCredential = await identityClient.GetCredentialsForIdentityAsync(idResponseId.IdentityId, new Dictionary <string, string> { { "cognito-idp.us-east-1.amazonaws.com/" + cognitoUserPoolId, idToken } }).ConfigureAwait(false); if (idResponseCredential.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine(String.Format("Failed to get credentials for identity. Status code: {0} ", idResponseCredential.HttpStatusCode)); System.Environment.Exit(1); } var cognitoCredentials = new UserCognitoCredentials(idResponseCredential.Credentials); return(cognitoCredentials); }
public async Task <bool> Login(string email, string password) { // Debug.Log("Login: "******", " + password); CognitoUserPool userPool = new CognitoUserPool(userPoolId, AppClientID, _provider); CognitoUser user = new CognitoUser(email, AppClientID, userPool, _provider); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = password }; try { AuthFlowResponse authFlowResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); _userid = await GetUserIdFromProvider(authFlowResponse.AuthenticationResult.AccessToken); // Debug.Log("Users unique ID from cognito: " + _userid); UserSessionCache userSessionCache = new UserSessionCache( authFlowResponse.AuthenticationResult.IdToken, authFlowResponse.AuthenticationResult.AccessToken, authFlowResponse.AuthenticationResult.RefreshToken, _userid); SaveDataManager.SaveJsonData(userSessionCache); // This how you get credentials to use for accessing other services. // This IdentityPool is your Authorization, so if you tried to access using an // IdentityPool that didn't have the policy to access your target AWS service, it would fail. _cognitoAWSCredentials = user.GetCognitoAWSCredentials(IdentityPool, Region); _user = user; return(true); } catch (Exception e) { Debug.Log("Login failed, exception: " + e); return(false); } }
public void Login() { Debug.Log("DOING: Login"); _user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = "******" }, r => { if (r.Exception != null) { Debug.LogException(r.Exception); return; } if (r.Result.AuthenticationResult != null) { Debug.Log("r.Result.AuthenticationResult.AccessToken: " + r.Result.AuthenticationResult.AccessToken); Debug.Log("r.Result.AuthenticationResult.IdToken: " + r.Result.AuthenticationResult.IdToken); Debug.Log("r.Result.AuthenticationResult.TokenType: " + r.Result.AuthenticationResult.TokenType); ICognitoAWSCredentials credentials = _user.GetCognitoAWSCredentials(IdentityPoolId, RegionEndpoint.GetBySystemName(Region), _aws); credentials.GetCredentialsAsync(creds => { if (creds.Exception != null) { Debug.LogException(creds.Exception); return; } Debug.Log("creds.Response.AccessKey: " + creds.Response.AccessKey); Debug.Log("creds.Response.SecretKey: " + creds.Response.SecretKey); Debug.Log("creds.Response.Token: " + creds.Response.Token); }); } else { Debug.Log("r.Result.ChallengeName: " + r.Result.ChallengeName); } }); }
public void LoginUser() { try { AmazonCognitoIdentityProviderClient _provider = new AmazonCognitoIdentityProviderClient((AWSCredentials) new AnonymousAWSCredentials(), RegionEndpoint.APSoutheast2); CognitoUserPool pool = new CognitoUserPool(AWS_USER_POOL_ID, AWS_CLIENT_ID, _provider); CognitoUser cognitoUser = new CognitoUser(AWS_Username, AWS_CLIENT_ID, pool, _provider); cognitoUser.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = AWS_Password }).Wait(); COGNITO_USER = cognitoUser; COGNITO_AWS_CREDENTIALS = COGNITO_USER.GetCognitoAWSCredentials(AWS_POOL_ID, AWS_REGION_ENDPOINT); AWS_CREDENTIALS = COGNITO_AWS_CREDENTIALS.GetCredentials(); } catch (Exception ex) { throw ex; } }
public virtual async Task <string> GetIdentityToken() { if (CognitoUser == null) { return(null); // Need to authenticate user first! } if (!string.IsNullOrEmpty(identityPoolId)) { // Using Identity Pools //var credentials = new CognitoAWSCredentials(IdentityPoolId, RegionEndpoint); CognitoAWSCredentials credentials = CognitoUser.GetCognitoAWSCredentials(identityPoolId, regionEndpoint); try { var IpIdentity = await credentials.GetIdentityIdAsync(); Debug.WriteLine($" IpIdentity {IpIdentity}"); return(IpIdentity); } catch (Exception e) { Debug.WriteLine($"{e.Message}"); return(null); } } // Using UserPools directly if (CognitoUser.SessionTokens.IsValid()) { return(CognitoUser.SessionTokens.IdToken); } if (await RefreshTokenAsync()) { return(CognitoUser.SessionTokens.IdToken); } return(null); }
private void NaviView_LandingLoginUpdate() { credentials = userF.GetCognitoAWSCredentials(identityID, RegionEndpoint.USEast1); }
private async Task <AuthEventEnum> NextChallenge(AuthEventEnum lastAuthEventEnum = AuthEventEnum.AuthChallenge) { try { if (!HasChallenge) { switch (CurrentAuthProcess) { case AuthProcessEnum.None: return(AuthEventEnum.Alert_NothingToDo); case AuthProcessEnum.ResettingPassword: CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.PasswordResetDone); case AuthProcessEnum.SigningUp: if (HasChallenge) { return(AuthEventEnum.AuthChallenge); } if (!IsLoginFormatOk) { AuthChallengeList.Add(AuthChallengeEnum.Login); } else if (!IsPasswordFormatOk) { AuthChallengeList.Add(AuthChallengeEnum.Password); } else if (!IsEmailFormatOk) { AuthChallengeList.Add(AuthChallengeEnum.Email); } if (HasChallenge) { return(AuthEventEnum.AuthChallenge); } if (!IsCodeVerified) { // Request Auth Code var signUpRequest = new SignUpRequest() { ClientId = clientId, Password = password, Username = login }; signUpRequest.UserAttributes.Add( new AttributeType() { Name = "email", Value = email }); // This call may throw an exception var result = await providerClient.SignUpAsync(signUpRequest).ConfigureAwait(false); if (!AuthChallengeList.Contains(AuthChallengeEnum.Code)) { AuthChallengeList.Add(AuthChallengeEnum.Code); } return(AuthEventEnum.AuthChallenge); } CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.SignedUp); case AuthProcessEnum.SigningIn: if (authFlowResponse != null && authFlowResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) // Update Passsword { if (!AuthChallengeList.Contains(AuthChallengeEnum.NewPassword)) { AuthChallengeList.Add(AuthChallengeEnum.NewPassword); } authFlowResponse = null; return(AuthEventEnum.AuthChallenge); } // Grab JWT from login to User Pools to extract User Pool Identity //var token = new JwtSecurityToken(jwtEncodedString: CognitoUser.SessionTokens.IdToken); //UpIdentity = token.Claims.First(c => c.Type == "sub").Value; // JWT sub cliam contains User Pool Identity //// Note: creates Identity Pool identity if it doesn't exist Credentials = CognitoUser.GetCognitoAWSCredentials(identityPoolId, regionEndpoint); IsSignedIn = true; CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.SignedIn); case AuthProcessEnum.UpdatingEmail: if (!IsCodeVerified) { AuthChallengeList.Add(AuthChallengeEnum.Code); return(AuthEventEnum.VerificationCodeSent); } CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.EmailUpdateDone); case AuthProcessEnum.UpdatingPassword: await CognitoUser.ChangePasswordAsync(password, newPassword).ConfigureAwait(false); CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.PasswordUpdateDone); case AuthProcessEnum.UpdatingPhone: CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.PhoneUpdateDone); } } } catch (UsernameExistsException) { return(AuthEventEnum.Alert_LoginAlreadyUsed); } catch (InvalidParameterException) { return(AuthEventEnum.Alert_InternalProcessError); } catch (InvalidPasswordException) { return(AuthEventEnum.Alert_PasswordFormatRequirementsFailed); } catch (TooManyRequestsException) { return(AuthEventEnum.Alert_TooManyAttempts); } catch (TooManyFailedAttemptsException) { return(AuthEventEnum.Alert_TooManyAttempts); } catch (PasswordResetRequiredException) { return(AuthEventEnum.Alert_PasswordResetRequiredException); } catch (Exception e) { Debug.WriteLine($"SignUp() threw an exception {e}"); return(AuthEventEnum.Alert_Unknown); } return(lastAuthEventEnum); }
private async void button1_Click(object sender, EventArgs e) { AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Amazon.RegionEndpoint.USEast2); String AccessToken = ""; CognitoUserPool userPool = new CognitoUserPool("us-east-2_5823vgrxD", "7dpaqpkf9b5pjp9gg94k3gndld", provider); CognitoUser user = new CognitoUser("AppUser2", "7dpaqpkf9b5pjp9gg94k3gndld", userPool, provider); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = "******" }; AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) { String NewPassword; frmEnterNewPassword f = new frmEnterNewPassword(); if (f.ShowDialog() == DialogResult.OK) { NewPassword = f.Controls["txtPassword"].Text; authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest() { SessionID = authResponse.SessionID, NewPassword = NewPassword }); AccessToken = authResponse.AuthenticationResult.AccessToken; } } else { AccessToken = authResponse.AuthenticationResult.AccessToken; } CognitoAWSCredentials credentials = user.GetCognitoAWSCredentials("us-east-2:bd9037c3-26d6-432a-a6a9-9d66281f49ba", Amazon.RegionEndpoint.USEast2); // CognitoAWSCredentials credentials = new CognitoAWSCredentials("us-east-2:bd9037c3-26d6-432a-a6a9-9d66281f49ba", Amazon.RegionEndpoint.USEast2); // credentials.AddLogin("www.amazon.com", AccessToken); //credentials. //Cognitocr using (var client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.USEast2)) { //var response1 = // await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false); //client.DeleteBucketAsync("Kalle"); //client.ListVersionsAsync("ssdfsdf"); ListBucketsResponse response = await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false); foreach (S3Bucket bucket in response.Buckets) { Console.WriteLine(bucket.BucketName); } } }
public async Task <bool> RefreshSession() { Debug.Log("RefreshSession"); DateTime issued = DateTime.Now; UserSessionCache userSessionCache = new UserSessionCache(); SaveDataManager.LoadJsonData(userSessionCache); if (userSessionCache != null && userSessionCache._refreshToken != null && userSessionCache._refreshToken != "") { try { CognitoUserPool userPool = new CognitoUserPool(userPoolId, AppClientID, _provider); // apparently the username field can be left blank for a token refresh request CognitoUser user = new CognitoUser("", AppClientID, userPool, _provider); // 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 user.SessionTokens = new CognitoUserSession( userSessionCache.getIdToken(), userSessionCache.getAccessToken(), userSessionCache.getRefreshToken(), issued, DateTime.Now.AddDays(30)); // TODO: need to investigate further. // It was my understanding that this should be set to when your refresh token expires... // Attempt refresh token call AuthFlowResponse authFlowResponse = await user.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest { AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH }) .ConfigureAwait(false); // Debug.Log("User Access Token after refresh: " + token); Debug.Log("User refresh token successfully updated!"); // update session cache UserSessionCache userSessionCacheToUpdate = new UserSessionCache( authFlowResponse.AuthenticationResult.IdToken, authFlowResponse.AuthenticationResult.AccessToken, authFlowResponse.AuthenticationResult.RefreshToken, userSessionCache.getUserId()); SaveDataManager.SaveJsonData(userSessionCacheToUpdate); // update credentials with the latest access token _cognitoAWSCredentials = user.GetCognitoAWSCredentials(IdentityPool, Region); _user = user; return(true); } catch (NotAuthorizedException ne) { // 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) Debug.Log("NotAuthorizedException: " + ne); } catch (WebException webEx) { // we get a web exception when we cant connect to aws - means we are offline Debug.Log("WebException: " + webEx); } catch (Exception ex) { Debug.Log("Exception: " + ex); } } return(false); }