Пример #1
0
        public async Task <AWSCredentials> ResolveAWSCredentials(string profileName, string lastUsedProfileName)
        {
            AWSCredentials credentials;

            var chain = new CredentialProfileStoreChain();

            if (!string.IsNullOrEmpty(profileName))
            {
                if (chain.TryGetAWSCredentials(profileName, out credentials) &&
                    await CanLoadCredentials(credentials))
                {
                    _toolInteractiveService.WriteLine($"Configuring AWS Credentials from Profile {profileName}.");
                    return(credentials);
                }
            }

            if (!string.IsNullOrEmpty(lastUsedProfileName) &&
                chain.TryGetAWSCredentials(lastUsedProfileName, out credentials) &&
                await CanLoadCredentials(credentials))
            {
                _toolInteractiveService.WriteLine($"Configuring AWS Credentials with previous configured profile value {lastUsedProfileName}.");
                return(credentials);
            }

            try
            {
                credentials = FallbackCredentialsFactory.GetCredentials();

                if (await CanLoadCredentials(credentials))
                {
                    _toolInteractiveService.WriteLine("Configuring AWS Credentials using AWS SDK credential search.");
                    return(credentials);
                }
            }
            catch (AmazonServiceException)
            {
                // FallbackCredentialsFactory throws an exception if no credentials are found. Burying exception because if no credentials are found
                // we want to continue and ask the user to select a profile.
            }

            var sharedCredentials = new SharedCredentialsFile();

            if (sharedCredentials.ListProfileNames().Count == 0)
            {
                _toolInteractiveService.WriteErrorLine("Unable to resolve AWS credentials to access AWS.");
                throw new NoAWSCredentialsFoundException();
            }

            var consoleUtilities    = new ConsoleUtilities(_toolInteractiveService);
            var selectedProfileName = consoleUtilities.AskUserToChoose(sharedCredentials.ListProfileNames(), "Select AWS Credentials Profile", null);

            if (!chain.TryGetAWSCredentials(selectedProfileName, out credentials) ||
                !(await CanLoadCredentials(credentials)))
            {
                _toolInteractiveService.WriteErrorLine($"Unable to create AWS credentials for profile {selectedProfileName}.");
                throw new NoAWSCredentialsFoundException();
            }

            return(credentials);
        }
Пример #2
0
        /// <summary>
        /// Constructs a new <see cref="AmazonServiceAccess"/> instance to work with AWS services.
        /// </summary>
        /// <param name="awsRegion">The region to use for the connection.</param>
        /// <param name="awsProfile">The name of the profile to get credentials from if not the 'default' one.</param>
        /// <exception cref="AmazonServiceException">
        /// Thrown when a custom and a default profile can't be found in <see cref="CredentialProfileStoreChain"/>CredentialProfileStoreChain.
        /// </exception>
        public AmazonServiceAccess(string awsRegion, string awsProfile = "default")
        {
            _region = RegionEndpoint.GetBySystemName(awsRegion);

            var chain = new CredentialProfileStoreChain();

            // Attempts to use a default profile if a custom profile is not found.
            if (!chain.TryGetAWSCredentials(awsProfile, out _awsCredentials) &&
                !chain.TryGetAWSCredentials("default", out _awsCredentials))
            {
                throw new AmazonServiceException("Unable to find AWS service credentials.");
            }
        }
Пример #3
0
        /// <summary>
        ///     Uploads the file asynchronous.
        /// </summary>
        /// <returns></returns>
        private static async Task UploadFileAsync()
        {
            try
            {
                var sw = Stopwatch.StartNew();
                var credentialProfileStoreChain = new CredentialProfileStoreChain();
                credentialProfileStoreChain.TryGetAWSCredentials("basic_profile", out var defaultCredentials);

                IAmazonS3 s3Client = new AmazonS3Client(defaultCredentials, BucketRegion);

                var fileTransferUtility = new TransferUtility(s3Client);
                // Option 1. Upload a file. The file name is used as the object key name.
                await fileTransferUtility.UploadAsync(FilePath, BucketName);

                sw.Stop();

                Console.WriteLine("Upload completed in {0} seconds", sw.Elapsed.TotalSeconds);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
Пример #4
0
        /// <summary>
        ///     Uploads the file asynchronous.
        /// </summary>
        /// <param name="fileToUpload">The file to upload.</param>
        /// <param name="keyname">The keyname.</param>
        /// <returns></returns>
        private static async Task UploadFileAsync(Stream fileToUpload, string keyname)
        {
            try
            {
                var sw = Stopwatch.StartNew();
                var credentialProfileStoreChain = new CredentialProfileStoreChain();
                credentialProfileStoreChain.TryGetAWSCredentials("basic_profile", out var defaultCredentials);

                IAmazonS3 s3Client = new AmazonS3Client(defaultCredentials, BucketRegion);

                var fileTransferUtility = new TransferUtility(s3Client);

                // Option 3. Upload data from a type of System.IO.Stream.
                await fileTransferUtility.UploadAsync(fileToUpload,
                                                      BucketName, keyname);

                sw.Stop();

                Console.WriteLine("UploadWithFileStream completed in {0}seconds", sw.Elapsed.TotalSeconds);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
Пример #5
0
        private static (AWSCredentials Creds, RegionEndpoint Region) GetAWSConfig(string profileName = null)
        {
            if (!string.IsNullOrEmpty(profileName))
            {
                var            chain = new CredentialProfileStoreChain();
                AWSCredentials creds;
                RegionEndpoint region;
                if (chain.TryGetProfile(profileName, out var profile))
                {
                    region = profile.Region;
                }
                else
                {
                    throw new ArgumentException($"No region profile with the name '{profileName}' was found.");
                }

                if (chain.TryGetAWSCredentials(profileName, out var credentials))
                {
                    creds = credentials;
                }
                else
                {
                    throw new ArgumentException($"No credential profile with credentials found with the name '{profileName}'.");
                }
            }

            return(FallbackCredentialsFactory.GetCredentials(), FallbackRegionFactory.GetRegionEndpoint());
        }
Пример #6
0
        public static async void UploadCompressedFile(string archiveFileName)
        {
            var keyName = Path.GetFileName(archiveFileName);

            try
            {
                var            chain = new CredentialProfileStoreChain();
                AWSCredentials awsCredentials;
                if (chain.TryGetAWSCredentials("playpen", out awsCredentials))
                {
                    var amazonS3Client             = new AmazonS3Client(awsCredentials, bucketRegion);
                    var fileTransferUtility        = new TransferUtility(amazonS3Client);
                    var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                    {
                        BucketName = bucketName,
                        Key        = keyNamePrefix + keyName,
                        FilePath   = archiveFileName
                    };
                    await fileTransferUtility.UploadAsync(fileTransferUtilityRequest);
                }
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
Пример #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDefaultAWSOptions(this.Configuration.GetAWSOptions());

            AWSOptions awsOptions             = Configuration.GetAWSOptions();
            CredentialProfileStoreChain chain = new CredentialProfileStoreChain(awsOptions.ProfilesLocation);

            if (chain.TryGetAWSCredentials(awsOptions.Profile, out AWSCredentials result))
            {
                ImmutableCredentials credentials = result.GetCredentials();

                Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", credentials.AccessKey);
                Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", credentials.SecretKey);
            }
            else
            {
                throw new Exception("Could not get Amazon credentials");
            }

            Environment.SetEnvironmentVariable("AWS_REGION", awsOptions.Region.SystemName);

            services.AddAWSService <IAmazonS3>();
        }
Пример #8
0
		string mWSAuthToken = "amzn.mws.10b0d30f-3c9c-fa00-c792-e9142f66a94c"; // me
																			   //string mWSAuthToken = "amzn.mws.c2b0d4ad-e73e-b729-d3a1-b0998fcd6a9f"; // RC
		public FeedsTests()
		{
			var chain = new CredentialProfileStoreChain();
			AWSCredentials awsCredentials;
			chain.TryGetAWSCredentials("DD MWS", out awsCredentials);
			creds = awsCredentials.GetCredentials();
		}
        public SQSBufferedConsumerTests()
        {
            //Must have credentials stored in the SDK Credentials store or shared credentials file
            var credentialChain = new CredentialProfileStoreChain();

            if (credentialChain.TryGetAWSCredentials("default", out var credentials) && credentialChain.TryGetProfile("default", out var profile))
            {
                var awsConnection = new AWSMessagingGatewayConnection(credentials, profile.Region);

                ChannelFactory channelFactory = new ChannelFactory(awsConnection, new SqsMessageConsumerFactory(awsConnection));
                var            name           = Guid.NewGuid().ToString();

                //we need the channel to create the queues and notifications
                channelFactory.CreateChannel(new Connection <MyCommand>(
                                                 name: new ConnectionName(name),
                                                 channelName: new ChannelName(name),
                                                 routingKey: new RoutingKey(_topicName),
                                                 bufferSize: BUFFER_SIZE
                                                 ));

                //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel
                //just for the tests, so create a new consumer from the properties
                _consumer = new SqsMessageConsumer(awsConnection, new ChannelName(name).ToValidSQSQueueName(), BUFFER_SIZE);

                _messageProducer = new SqsMessageProducer(awsConnection);
            }
        }
Пример #10
0
        private static void LocalProfileTest()
        {
            var chain          = new CredentialProfileStoreChain();
            var awsCredentials = default(AWSCredentials);

            if (chain.TryGetAWSCredentials("default", out awsCredentials))
            {
                var aws = awsCredentials.GetCredentials();

                var request = new AwsApiGatewayRequest()
                {
                    RegionName    = "ap-southeast-2",
                    Host          = apiEndpoint,
                    AccessKey     = aws.AccessKey,
                    SecretKey     = aws.SecretKey,
                    AbsolutePath  = apiEndpointStaging,
                    JsonData      = "245",
                    RequestMethod = HttpMethod.Post
                };
                var apiRequest = new ApiRequest(request);
                var response   = apiRequest.GetResponse();

                Console.WriteLine(response.ContentLength);
            }
        }
Пример #11
0
        private static CloudConfig CreateCloudConfig()
        {
            AWSCredentials credentials;
            bool           isInAws = false;

            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            if (chain.TryGetAWSCredentials("chessdb-prod", out awsCredentials))
            {
                credentials = awsCredentials;
            }
            else
            {
                credentials = FallbackCredentialsFactory.GetCredentials();
                isInAws     = true;
            }

            var options = new AWSOptions()
            {
                Credentials = credentials,
                Region      = RegionEndpoint.USEast2,
            };

            string stage = Environment.GetEnvironmentVariable("JANUS_STAGE") ?? "prod";

            return(new CloudConfig()
            {
                Stage = stage,
                Options = options,
                IsInCloud = isInAws,
            });
        }
Пример #12
0
        public SqsMessageProducerSendTests()
        {
            _myCommand = new MyCommand {
                Value = "Test"
            };
            _correlationId = Guid.NewGuid();
            _replyTo       = "http:\\queueUrl";
            _contentType   = "text\\plain";
            _topicName     = _myCommand.GetType().FullName.ToValidSNSTopicName();

            _message = new Message(
                new MessageHeader(_myCommand.Id, _topicName, MessageType.MT_COMMAND, _correlationId, _replyTo, _contentType),
                new MessageBody(JsonConvert.SerializeObject((object)_myCommand))
                );

            //Must have credentials stored in the SDK Credentials store or shared credentials file
            var credentialChain = new CredentialProfileStoreChain();

            if (credentialChain.TryGetAWSCredentials("default", out var credentials) && credentialChain.TryGetProfile("default", out var profile))
            {
                var awsConnection = new AWSMessagingGatewayConnection(credentials, profile.Region);

                _channelFactory = new ChannelFactory(awsConnection, new SqsMessageConsumerFactory(awsConnection));

                _channel = _channelFactory.CreateChannel(_connection);

                _messageProducer = new SqsMessageProducer(awsConnection);
            }
        }
Пример #13
0
        public config(string aws_credential_profile_name)
        {
            this.aws_credential_profile_name = aws_credential_profile_name;

            InitializeComponent();

            //大きさ固定
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            //フォームが最大化されないようにする
            this.MaximizeBox = false;
            //フォームが最小化されないようにする
            this.MinimizeBox = false;

            // 参考:http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html
            // プロファイルを読み込む
            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            if (chain.TryGetAWSCredentials(aws_credential_profile_name, out awsCredentials))
            {
                //読めたのでセット
                var cretiential = awsCredentials.GetCredentials();
                Txt_AWS_AccessKey.Text = cretiential.AccessKey;
                Txt_AWS_SecretKey.Text = cretiential.SecretKey;
            }
            else
            {
                //読めなかったのでクリア
                Txt_AWS_AccessKey.Text = "";
                Txt_AWS_SecretKey.Text = "";
            }
        }
        protected AWSCredentials DetermineAWSCredentials()
        {
            AWSCredentials credentials;

            if (this.Credentials != null)
            {
                credentials = this.Credentials;
            }
            else
            {
                var profile = this.Profile;
                if (string.IsNullOrEmpty(profile))
                {
                    profile = DefaultConfig[CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE.Switch] as string;
                }

                if (!string.IsNullOrEmpty(profile))
                {
                    var chain = new CredentialProfileStoreChain(this.ProfileLocation);
                    if (!chain.TryGetAWSCredentials(profile, out credentials))
                    {
                        throw new ToolsException($"Credentials for profile {profile} cannot be found", ToolsException.CommonErrorCode.ProfileNotFound);
                    }
                }
                else
                {
                    credentials = FallbackCredentialsFactory.GetCredentials();
                }
            }

            return(credentials);
        }
Пример #15
0
        public async Task <string> UploadFile(string fileName, Stream fileStream)
        {
            var chain = new CredentialProfileStoreChain();

            if (!chain.TryGetAWSCredentials("top_trumps", out var awsCredentials))
            {
                throw new Exception("AWS CREDENTIALS NOT FOUND");
            }

            var key = $"{Guid.NewGuid()}.{fileName}";

            using var client = new AmazonS3Client(awsCredentials);

            var uploadRequest = new TransferUtilityUploadRequest
            {
                InputStream = fileStream,
                Key         = key,
                BucketName  = _configuration["AWS:S3BucketName"],
                CannedACL   = S3CannedACL.PublicRead
            };

            var fileTransferUtility = new TransferUtility(client);
            await fileTransferUtility.UploadAsync(uploadRequest);

            return(GetUrl(key));
        }
Пример #16
0
 public DynamoDBHelper(ILambdaContext mContext, bool isLocalDebug)
 {
     try
     {
         this.context      = mContext;
         this.isLocalDebug = isLocalDebug;
         if (isLocalDebug)
         {
             var            chain = new CredentialProfileStoreChain();
             AWSCredentials awsCredentials;
             if (chain.TryGetAWSCredentials(Constants.AWSProfileName, out awsCredentials))
             {
                 // use awsCredentials
                 client = new AmazonDynamoDBClient(awsCredentials, Amazon.RegionEndpoint.USEast1);
             }
         }
         else
         {
             client = new AmazonDynamoDBClient();
         }
     }
     catch (Exception ex)
     {
         context.Logger.LogLine("DynamoDBHelper  => " + ex.StackTrace);
     }
 }
Пример #17
0
        public static bool TryGetClient(string profile, TelemetryConfiguration config, out ITelemetryClient client, bool enabledDefaultCredentials = false)
        {
            client = null;
            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            if (enabledDefaultCredentials)
            {
                awsCredentials = FallbackCredentialsFactory.GetCredentials();
                if (awsCredentials == null)
                {
                    return(false);
                }
            }
            else
            {
                if (!chain.TryGetAWSCredentials(profile, out awsCredentials))
                {
                    return(false);
                }
            }
            if (awsCredentials != null)
            {
                client = new TelemetryClient(awsCredentials, new TelemetryClientConfig
                {
                    RegionEndpoint = RegionEndpoint.GetBySystemName(config.Region),
                    MaxErrorRetry  = 2,
                    ServiceURL     = config.InvokeUrl,
                });
                return(true);
            }
            return(false);
        }
Пример #18
0
        public static void Main()
        {
#if RUN_LOCAL
            var config = new AmazonSQSConfig();
            config.ServiceURL = "http://127.0.0.1:4100";
            var sqs = new AmazonSQSClient(config);
#else
            var chain = new CredentialProfileStoreChain();
            // TODO: fill your credentials!
            if (!chain.TryGetAWSCredentials("DevDaysEurope2019", out var awsCredentials))
            {
                Console.WriteLine("Can't find profile, configure profile and try again");

                return;
            }

            var sqs = new AmazonSQSClient(awsCredentials, RegionEndpoint.EUCentral1);
#endif
            var wrapper = new QueueWrapper(sqs);

            var queueUrl = wrapper.GetQueueUrl(QueueName).Result;
            Console.WriteLine($"Listening for messages, queue url: {queueUrl}");

            do
            {
                var message = wrapper.GetNextMessage(queueUrl).Result;

                Console.WriteLine(message);
                Console.WriteLine("-----------------");
            } while (true);
        }
Пример #19
0
        private AWSCredentials GetAwsCredentials(AWSS3Labs.Web.Configuration.AmazonS3Config config)
        {
            if (!string.IsNullOrWhiteSpace(config.Profile))
            {
                var credentialProfileStoreChain = new CredentialProfileStoreChain();

                if (credentialProfileStoreChain.TryGetAWSCredentials(config.Profile, out AWSCredentials profileCredentials))
                {
                    return(profileCredentials);
                }
                else
                {
                    throw new AmazonClientException($"Failed to find AWS credentials for the profile {config.Profile}");
                }
            }

            if (!string.IsNullOrEmpty(config.AccessKeyId) && !string.IsNullOrWhiteSpace(config.SecretAccessKey))
            {
                return(new BasicAWSCredentials(config.AccessKeyId, config.SecretAccessKey));
            }

            var credentials = FallbackCredentialsFactory.GetCredentials();

            if (credentials == null)
            {
                throw new AmazonClientException("Failed to find AWS Credentials for constructing AWS service client");
            }

            return(credentials);
        }
Пример #20
0
        public Form1()
        {
            InitializeComponent();

            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            if (chain.TryGetAWSCredentials("default", out awsCredentials))
            {
                var keys = awsCredentials.GetCredentials();
                client      = new AmazonSimpleNotificationServiceClient(region: region, awsAccessKeyId: keys.AccessKey, awsSecretAccessKey: keys.SecretKey);
                soundWriter = new SoundS3Writer(keys.AccessKey, keys.SecretKey, region);
                //soundWriter = new SoundFileWriter();
            }
            request = new PublishRequest
            {
                Message  = message,
                TopicArn = topicArn
            };



            waveIn = new WaveInEvent();
            waveIn.DataAvailable += OnDataAvailable;
            waveIn.StartRecording();
        }
Пример #21
0
        private static AWSCredentials GetDefaultStoredProfile()
        {
            var credentialProfileStoreChain = new CredentialProfileStoreChain();

            return(credentialProfileStoreChain.TryGetAWSCredentials("default", out var credentials)
                ? credentials
                : throw new AmazonClientException("Unable to find a default profile in CredentialProfileStoreChain."));
        }
Пример #22
0
        private static AWSCredentials GetNamedStoredProfile(string profileName)
        {
            var credentialProfileStoreChain = new CredentialProfileStoreChain();

            return(credentialProfileStoreChain.TryGetAWSCredentials(profileName, out var credentials)
                ? credentials
                : null);
        }
Пример #23
0
        private AWSCredentials GetAwsCredential()
        {
            var chain          = new CredentialProfileStoreChain();
            var awsCredentials = default(AWSCredentials);

            chain.TryGetAWSCredentials(_config.LocaAwsProfile, out awsCredentials);
            return(awsCredentials);
        }
Пример #24
0
        protected AWSCredentials DetermineAWSCredentials()
        {
            if (this._resolvedCredentials != null)
            {
                return(this._resolvedCredentials);
            }

            if (this.Credentials != null)
            {
                this._resolvedCredentials = this.Credentials;
            }
            else
            {
                var awsAccessKeyId = GetStringValueOrDefault(this.AWSAccessKeyId, CommonDefinedCommandOptions.ARGUMENT_AWS_ACCESS_KEY_ID, false);
                var profile        = this.GetStringValueOrDefault(this.Profile, CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE, false);

                if (!string.IsNullOrEmpty(awsAccessKeyId))
                {
                    var awsSecretKey    = GetStringValueOrDefault(this.AWSSecretKey, CommonDefinedCommandOptions.ARGUMENT_AWS_SECRET_KEY, false);
                    var awsSessionToken = GetStringValueOrDefault(this.AWSSessionToken, CommonDefinedCommandOptions.ARGUMENT_AWS_SESSION_TOKEN, false);

                    if (string.IsNullOrEmpty(awsSecretKey))
                    {
                        throw new ToolsException("An AWS access key id was specified without a required AWS secret key. Either set an AWS secret key or remove the AWS access key id and use profiles for credentials.", ToolsException.CommonErrorCode.InvalidCredentialConfiguration);
                    }

                    if (string.IsNullOrEmpty(awsSessionToken))
                    {
                        this._resolvedCredentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretKey);
                    }
                    else
                    {
                        this._resolvedCredentials = new SessionAWSCredentials(awsAccessKeyId, awsSecretKey, awsSessionToken);
                    }
                }
                else if (!string.IsNullOrEmpty(profile))
                {
                    var chain = new CredentialProfileStoreChain(this.ProfileLocation);
                    if (!chain.TryGetAWSCredentials(profile, out this._resolvedCredentials))
                    {
                        this._resolvedCredentials = FallbackCredentialsFactory.GetCredentials();
                    }
                }
                else
                {
                    this._resolvedCredentials = FallbackCredentialsFactory.GetCredentials();
                }

                if (this._resolvedCredentials is AssumeRoleAWSCredentials)
                {
                    var assumeOptions = ((AssumeRoleAWSCredentials)this._resolvedCredentials).Options;
                    assumeOptions.MfaTokenCodeCallback = new AssumeRoleMfaTokenCodeCallback(assumeOptions).Execute;
                }
            }

            return(this._resolvedCredentials);
        }
Пример #25
0
        public static AWSCredentials GetCredential(string profileName)
        {
            var chain = new CredentialProfileStoreChain();

            if (chain.TryGetProfile(profileName, out var profile) && chain.TryGetAWSCredentials(profileName, out var credentials))
            {
                return(credentials);
            }
            throw new NullReferenceException($"{nameof(profileName)} not found from exsiting profile list. Make sure you have set Profile");
        }
Пример #26
0
        private void UseAmazonWebServices(IConfiguration configuration)
        {
            AWSOptions = configuration.GetAWSOptions("AWS");
            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            chain.TryGetAWSCredentials(AWSOptions.Profile ?? "default", out awsCredentials);
            AWSOptions.Credentials = awsCredentials;
            S3BucketsOptions       = configuration.GetSection("AWS").GetSection("Buckets").Get <S3BucketsOptions>();
        }
Пример #27
0
        static AWSCredentials GetGasmonCredentials()
        {
            var chain = new CredentialProfileStoreChain();

            if (chain.TryGetAWSCredentials("gasmon", out var credentials))
            {
                return(credentials);
            }
            throw new InvalidOperationException("Missing AWS profile gasmon");
        }
Пример #28
0
        public FunctionTest()
        {
            AWSConfigs.AWSProfilesLocation = $"{Environment.GetEnvironmentVariable("UserProfile")}\\.aws\\credentials";
            AWSConfigs.AWSProfileName      = ProfileName;
            CredentialProfileStoreChain Chain = new CredentialProfileStoreChain();
            AWSCredentials Credentials;

            Chain.TryGetAWSCredentials(ProfileName, out Credentials);
            S3Client = new AmazonS3Client(Credentials);
        }
Пример #29
0
        internal static AWSCredentials GetCredentials(string profileName = "default")
        {
            var chain = new CredentialProfileStoreChain();

            if (chain.TryGetAWSCredentials(profileName, out var awsCredentials))
            {
                return(awsCredentials);
            }
            throw new ArgumentOutOfRangeException(nameof(profileName), "The profile provided was not found.");
        }
Пример #30
0
 private void CreateClient()
 {
     if (this.service.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
         this.service.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
     {
         // Local DynamoDB instance (for testing)
         var credentials = new BasicAWSCredentials("dummy", "dummyKey");
         this.ddbClient = new AmazonDynamoDBClient(credentials, new AmazonDynamoDBConfig {
             ServiceURL = this.service
         });
     }
     else if (!string.IsNullOrEmpty(this.accessKey) && !string.IsNullOrEmpty(this.secretKey) && !string.IsNullOrEmpty(this.token))
     {
         // AWS DynamoDB instance (auth via explicit credentials and token)
         var credentials = new SessionAWSCredentials(this.accessKey, this.secretKey, this.token);
         this.ddbClient = new AmazonDynamoDBClient(credentials, new AmazonDynamoDBConfig {
             RegionEndpoint = AWSUtils.GetRegionEndpoint(this.service)
         });
     }
     else if (!string.IsNullOrEmpty(this.accessKey) && !string.IsNullOrEmpty(this.secretKey))
     {
         // AWS DynamoDB instance (auth via explicit credentials)
         var credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
         this.ddbClient = new AmazonDynamoDBClient(credentials, new AmazonDynamoDBConfig {
             RegionEndpoint = AWSUtils.GetRegionEndpoint(this.service)
         });
     }
     else if (!string.IsNullOrEmpty(this.profileName))
     {
         // AWS DynamoDB instance (auth via explicit credentials and token found in a named profile)
         var chain = new CredentialProfileStoreChain();
         if (chain.TryGetAWSCredentials(this.profileName, out var credentials))
         {
             this.ddbClient = new AmazonDynamoDBClient(
                 credentials,
                 new AmazonDynamoDBConfig
             {
                 RegionEndpoint = AWSUtils.GetRegionEndpoint(this.service)
             });
         }
         else
         {
             throw new InvalidOperationException(
                       $"AWS named profile '{this.profileName}' provided, but credentials could not be retrieved");
         }
     }
     else
     {
         // AWS DynamoDB instance (implicit auth - EC2 IAM Roles etc)
         this.ddbClient = new AmazonDynamoDBClient(new AmazonDynamoDBConfig {
             RegionEndpoint = AWSUtils.GetRegionEndpoint(this.service)
         });
     }
 }