Example #1
0
        public IAmazonSimpleNotificationService GetSnsClient(RegionEndpoint region)
        {
            var credentials  = new AnonymousAWSCredentials();
            var clientConfig = new AmazonSimpleNotificationServiceConfig
            {
                RegionEndpoint = region,
                ServiceURL     = ServiceUrl.ToString()
            };

            return(new AmazonSimpleNotificationServiceClient(credentials, clientConfig));
        }
Example #2
0
        public SqsMessageProducerRequeueTests()
        {
            var messageHeader = new MessageHeader(Guid.NewGuid(), "TestSqsTopic", MessageType.MT_COMMAND);

            messageHeader.UpdateHandledCount();
            _sentMessage = new Message(messageHeader, new MessageBody("test content"));

            var credentials = new AnonymousAWSCredentials();

            _sender            = new SqsMessageProducer(credentials);
            _receiver          = new SqsMessageConsumer(credentials, _queueUrl);
            _testQueueListener = new TestAWSQueueListener(credentials, _queueUrl);
        }
Example #3
0
        public VierAuthService
        (
            ILogger <VierAuthService> logger,
            IOptionsMonitor <VierConfiguration> configMonitor
        )
        {
            _logger        = logger;
            _configuration = configMonitor.CurrentValue;
            var cred = new AnonymousAWSCredentials();

            _provider = new AmazonCognitoIdentityProviderClient(cred, RegionEndpoint.EUWest1);
            _userPool = new CognitoUserPool(USER_POOL_ID, CLIENT_ID, _provider);
        }
        public void GetCredentials_GivenSetCredentials_ThenReturnsSame()
        {
            var options = new AmazonSqsOptions();

            var expected = new AnonymousAWSCredentials();

            options.SetCredentials(expected);

            var credentials = options.GetCredentials();
            var actual      = Assert.IsType <AnonymousAWSCredentials>(credentials);

            Assert.Same(expected, actual);
        }
        /// <summary>
        /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
        /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the
        /// region the Lambda function is executed in.
        /// </summary>
        public Function()
        {
            AWSCredentials creds = new AnonymousAWSCredentials();

            AmazonS3Config config = new AmazonS3Config
            {
                ProxyHost      = "aws-localstack",
                ProxyPort      = 4572,
                RegionEndpoint = RegionEndpoint.GetBySystemName("us-east-1"),
                ServiceURL     = "http://aws-localstack:4572",
                UseHttp        = true,
                ForcePathStyle = true,
            };

            s3Client = new AmazonS3Client(creds, config);
        }
        public void Establish()
        {
            var messageHeader = new MessageHeader(Guid.NewGuid(), "TestSqsTopic", MessageType.MT_COMMAND);

            messageHeader.UpdateHandledCount();
            _message = new Message(header: messageHeader, body: new MessageBody("test content"));

            var credentials = new AnonymousAWSCredentials();

            _sender            = new SqsMessageProducer(credentials);
            _receiver          = new SqsMessageConsumer(credentials, _queueUrl);
            _testQueueListener = new TestAWSQueueListener(credentials, _queueUrl);

            _sender.Send(_message);

            _listenedMessage = _receiver.Receive(1000);
        }
Example #7
0
        public S3Service(ApplicationConfig config, ILogger <S3Service> logger)
        {
            _config = config;
            _logger = logger;
            // var region = RegionEndpoint.GetBySystemName(_config.S3.AwsRegionEndpoint);
            // _s3Client = new AmazonS3Client(_config.S3.AwsAccessKeyId, _config.S3.AwsSecretAccessKey, region);
            AmazonS3Config s3Config = new AmazonS3Config
            {
                ServiceURL           = _config.S3.AwsEndpointUrl,
                UseHttp              = true,
                ForcePathStyle       = true,
                AuthenticationRegion = _config.S3.AwsRegionEndpoint,
            };
            AWSCredentials creds = new AnonymousAWSCredentials();

            _s3Client = new AmazonS3Client(creds, s3Config);
        }
Example #8
0
        /// <summary>
        /// Initializes a new MIC client instance using the specified
        /// MIC Manifest document.
        /// </summary>
        /// <param name="manifest"></param>
        protected MicClient(MicManifest manifest) : base()
        {
            Manifest = manifest ?? throw new ArgumentNullException(nameof(manifest));

            Config = new MicClientConfig()
            {
                RegionEndpoint = Manifest.AwsRegion
            };

            var anonymousCreds = new AnonymousAWSCredentials();

            cognitoClient = new AmazonCognitoIdentityClient(anonymousCreds, Config.Create <AmazonCognitoIdentityConfig>());
            stsClient     = new AmazonSecurityTokenServiceClient(anonymousCreds, Config.Create <AmazonSecurityTokenServiceConfig>());

            AwsCredentials = new CognitoAWSCredentials(accountId: null, identityPoolId: Manifest.IdentityPool,
                                                       unAuthRoleArn: null, authRoleArn: null,
                                                       cognitoClient, stsClient
                                                       );
        }
Example #9
0
        public static void Process(MemoryStream inStream, string fileName)
        {
            retStr = string.Empty;

            AWSCredentials creds  = new AnonymousAWSCredentials();
            AmazonS3Config config = new AmazonS3Config
            {
                ProxyHost      = "aws-localstack",
                ProxyPort      = 4572,
                RegionEndpoint = RegionEndpoint.GetBySystemName("us-east-1"),
                ServiceURL     = "http://aws-localstack:4572",
                UseHttp        = true,
                ForcePathStyle = true,
            };

            s3Client = new AmazonS3Client(creds, config);
            PrepareBucketAsync().Wait();
            S3BucketIOWorker(inStream, fileName).Wait();
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            if (this._ExecuteWithAnonymousCredentials)
            {
                _CurrentCredentials = new AnonymousAWSCredentials();
                WriteCredentialSourceDiagnostic("anonymous credentials");
            }
            else
            {
                AWSPSCredentials awsPSCredentials;
                if (!this.TryGetCredentials(Host, out awsPSCredentials, SessionState))
                {
                    ThrowExecutionError("No credentials specified or obtained from persisted/shell defaults.", this);
                }

                _CurrentCredentials = awsPSCredentials.Credentials;
                WriteCredentialSourceDiagnostic(awsPSCredentials);
            }

            this.TryGetRegion(string.IsNullOrEmpty(_DefaultRegion), out var region, out var regionSource, SessionState);

            _RegionEndpoint = region;

            if (_RegionEndpoint == null)
            {
                if (String.IsNullOrEmpty(_DefaultRegion))
                {
                    ThrowExecutionError("No region specified or obtained from persisted/shell defaults.", this);
                }
                else
                {
                    _RegionEndpoint = RegionEndpoint.GetBySystemName(_DefaultRegion);
                    WriteRegionSourceDiagnostic("built-in-default", _DefaultRegion);
                }
            }
            else
            {
                WriteRegionSourceDiagnostic(regionSource, region.SystemName);
            }
        }
Example #11
0
        public async Task UploadFile(string bucketName, string filePath)
        {
            // Even though Localstack ignores AWS credentials, if you don't have any set up, e.g. via `aws configure` (~/.aws/credentials), and you
            // try to invoke any methods on the S3 client you will get an HttpRequestException with a 'No route to host' error message, which is not helpful.
            // We are using anonymous credentials here to simply avoid this issue.
            // The AWS SDK will use any configured credentials if set up.
            // TODO: Add logic to use local AWS creds if set up, otherwise fall back to anonymous ones.
            var creds  = new AnonymousAWSCredentials();
            var config = new AmazonS3Config
            {
                ServiceURL = S3_URL,
                // Unless configured otherwise, by default Localstack only supports http.
                UseHttp = true,
                // Force the use of hostname/bucket/file pattern, instead of the default bucket.hostname/file, which will cause
                // domain name resolution issues.
                ForcePathStyle = true
            };

            using (var client = new AmazonS3Client(creds, config))
            {
                // Create the bucket if it doesn't already exist
                var bucket = await client.PutBucketAsync(new PutBucketRequest
                {
                    BucketName      = bucketName,
                    UseClientRegion = true
                });

                var list = await client.ListBucketsAsync();

                var transferUtility = new TransferUtility(client);
                var exists          = File.Exists(filePath);
                await transferUtility.UploadAsync(filePath, bucketName);

                var objects = await client.ListObjectsAsync(bucketName);
            }
        }
 /// <summary>
 /// Specifies that anonymous access to AWS should be used.
 /// </summary>
 /// <returns>
 /// The current <see cref="AwsClientFactoryBuilder"/>.
 /// </returns>
 public AwsClientFactoryBuilder WithAnonymousCredentials()
 {
     Credentials = new AnonymousAWSCredentials();
     return(this);
 }
Example #13
0
 private static void SetDefaults()
 {
     Credentials    = new AnonymousAWSCredentials();
     RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName(DefaultRegion);
 }
Example #14
0
        public async void SignUpNewUser(string email, string password, string familyName, string firstName, string phoneNumber, string deviceId)
        {
            AnonymousAWSCredentials             credentials = new AnonymousAWSCredentials();
            AmazonCognitoIdentityProviderClient provider    = new AmazonCognitoIdentityProviderClient(credentials, Amazon.RegionEndpoint.USEast2);

            CognitoUserPool pool = new CognitoUserPool(ConfigurationManager.AppSettings["USERPOOL_ID"], ConfigurationManager.AppSettings["CLIENT_ID"], provider, "");

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

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

            Dictionary <string, string> userAttributes = new Dictionary <string, string>(StringComparer.Ordinal)
            {
                { "email", email },
                { "family_name", familyName },
                { "given_name", firstName },
            };
            Dictionary <string, string> validationData = new Dictionary <string, string>(StringComparer.Ordinal)
            {
                { "email", email }
            };

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

            //Get the UsersVerificationCode programatically.
            Task <AdminConfirmSignUpResponse> myresponse = provider.AdminConfirmSignUpAsync(new AdminConfirmSignUpRequest {
                UserPoolId = ConfigurationManager.AppSettings["USERPOOL_ID"], Username = email
            });


            AdminUpdateUserAttributesRequest i = new AdminUpdateUserAttributesRequest();

            i.UserAttributes.Add(new AttributeType {
                Name = "email_verified", Value = "true"
            });
            i.UserPoolId = ConfigurationManager.AppSettings["USERPOOL_ID"];
            i.Username   = email;


            AdminUpdateUserAttributesResponse T = await provider.AdminUpdateUserAttributesAsync(i);

            Debug.Print(T.ToString());
            //          client.adminUpdateUserAttributes({
            //          UserAttributes:
            //              [{
            //              Name: 'phone_number_verified',
            //    Value: 'true'
            //            }, {
            //              Name: 'email_verified',
            //    Value: 'true'
            //           }
            //  // other user attributes like phone_number or email themselves, etc
            //],
            //UserPoolId: 'COGNITO_USER_POOL_ID_HERE',
            //Username: '******'


            //myresponse.res.
            // Debug.Print(myresponse.Result.ToString());
        }
Example #15
0
        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
                    {
                        var handler = new JwtSecurityTokenHandler();
                        var token   = handler.ReadJwtToken(context.AuthenticationResult?.AccessToken);
                        var groups  = token.Payload.ToArray().FirstOrDefault(p => p.Key == "cognito:groups").Value;

                        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,
                            IsAdmin = groups != null?groups.ToString().Contains("Admin") : false
                        });
                    }
                }
            }
            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));
        }
Example #16
0
        public async Task <string> GetUserToken(string username, string password)
        {
            var credentials = await CredentialHelper.GetCredentials();

            var AWS_REGION = credentials.Region;
            var POOL_NAME  = credentials.PoolName;
            AnonymousAWSCredentials cred = new AnonymousAWSCredentials();

            // Identify your Cognito UserPool Provider
            using (var provider = new Amazon.CognitoIdentityProvider.AmazonCognitoIdentityProviderClient(cred, AWS_REGION))
            {
                //Get the SRP variables A and a
                var TupleAa = AuthenticationHelper.CreateAaTuple();

                //Initiate auth with the generated SRP A
                var authResponse = await provider.InitiateAuthAsync(new InitiateAuthRequest
                {
                    ClientId       = credentials.ClientId,
                    AuthFlow       = Amazon.CognitoIdentityProvider.AuthFlowType.USER_SRP_AUTH,
                    AuthParameters = new Dictionary <string, string>()
                    {
                        { "USERNAME", username },
                        { "SRP_A", TupleAa.Item1.ToString(16) }
                    }
                });

                //Now with the authResponse containing the password challenge for us, we need to
                //set up a reply
                //ChallengeParameters SALT, SECRET_BLOCK, SRP_B, USERNAME, USER_ID_FOR_SRP


                DateTime timestamp = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now);
                //The timestamp format returned to AWS _needs_ to be in US Culture
                CultureInfo usCulture = new CultureInfo("en-US");
                String      timeStr   = timestamp.ToString("ddd MMM d HH:mm:ss \"UTC\" yyyy", usCulture);

                //Do the hard work to generate the claim we return to AWS
                byte[] claim = AuthenticationHelper.authenticateUser(authResponse.ChallengeParameters["USERNAME"],
                                                                     password,
                                                                     POOL_NAME,
                                                                     TupleAa,
                                                                     authResponse.ChallengeParameters["SALT"],
                                                                     authResponse.ChallengeParameters["SRP_B"],
                                                                     authResponse.ChallengeParameters["SECRET_BLOCK"],
                                                                     timeStr
                                                                     );


                String claimBase64 = System.Convert.ToBase64String(claim);

                //Our response to AWS. If successful it will return an object with Tokens,
                //if unsuccessful, it will throw an Exception that you should catch and handle.
                var resp = await provider.RespondToAuthChallengeAsync(new RespondToAuthChallengeRequest
                {
                    ChallengeName      = authResponse.ChallengeName,
                    ClientId           = credentials.ClientId,
                    ChallengeResponses = new Dictionary <string, string>()
                    {
                        { "PASSWORD_CLAIM_SECRET_BLOCK", authResponse.ChallengeParameters["SECRET_BLOCK"] },
                        { "PASSWORD_CLAIM_SIGNATURE", claimBase64 },
                        { "USERNAME", username },
                        { "TIMESTAMP", timeStr }
                    }
                });

                return(resp.AuthenticationResult.IdToken);
            }
        }