コード例 #1
0
        private static void Create2Profiles(SharedCredentialsFileTestFixture tester)
        {
            var options1 = new CredentialProfileOptions
            {
                AccessKey = "access_key1",
                SecretKey = "secret_key1"
            };
            CredentialProfile profile1 = new CredentialProfile("profile1", options1);

            var options2 = new CredentialProfileOptions
            {
                AccessKey = "access_key2",
                SecretKey = "secret_key2"
            };

            CredentialProfile profile2 = new CredentialProfile("profile2", options2);

            tester.CredentialsFile.RegisterProfile(profile1);
            tester.CredentialsFile.RegisterProfile(profile2);
        }
コード例 #2
0
        public void subeFile()
        {
            //_environment = environment;
            AmazonS3Config cfg = new AmazonS3Config();

            cfg.RegionEndpoint = bucketRegion;
            var options = new CredentialProfileOptions
            {
                AccessKey = "",
                SecretKey = ""
            };
            var profile = new CredentialProfile("basic_profile", options);

            profile.Region = RegionEndpoint.USEast1;
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);
            s3Client = new AmazonS3Client("", "", RegionEndpoint.EUWest2);
            UploadFileAsync().Wait();
        }
コード例 #3
0
        private void BtnGenerate_Click(object sender, EventArgs e)
        {
            string            title;
            string            message;
            DialogResult      result;
            MessageBoxButtons buttons;

            try
            {
                var options = new CredentialProfileOptions
                {
                    AccessKey = txtAccessKey.Text,
                    SecretKey = txtSecretKey.Text
                };
                var profile = new CredentialProfile("shared_profile", options);
                profile.Region = RegionEndpoint.APSoutheast2;
                var sharedFile = new SharedCredentialsFile();
                sharedFile.RegisterProfile(profile);
            }
            catch (Exception ex) {
                title   = "Ërror creating configuration file";
                message = ex.Message;
                buttons = MessageBoxButtons.OK;

                result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error);
                if (result == DialogResult.Yes)
                {
                    Close();
                }
            }
            title   = "";
            message = "Succesfully created configuration file";
            buttons = MessageBoxButtons.OK;

            result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Information);
            if (result == DialogResult.Yes)
            {
                Close();
            }
            Close();
        }
コード例 #4
0
        /// <summary>
        ///
        /// </summary>
        /// <returns>AWSCredential for the instance versions of the string</returns>
        public AWSCredentials GetAWSCredentials()
        {
            AWSCredentials credentials = null;

            var options = new CredentialProfileOptions()
            {
                AccessKey = this.AccessKey,
                SecretKey = this.SecretKey
            };

            CredentialProfile profile = new CredentialProfile("default", options);

            profile.Region = RegionEndpoint.USEast1;
            var sharedFile = new SharedCredentialsFile();

            sharedFile.RegisterProfile(profile);

            AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedFile, out credentials);

            return(credentials);
        }
コード例 #5
0
        private static (AWSCredentials, CredentialProfile, ICredentialProfileSource) loadCurrent()
        {
            CredentialProfile        profile       = null;
            ICredentialProfileSource profileSource = _sharedFile;

            if (Manager.Settings.profileSource.Equals("private"))
            {
                profileSource = _netSDKFile;
            }

            if (profileSource.TryGetProfile(Manager.Settings.profileName ?? "", out profile))
            {
                return(profile.GetAWSCredentials(profileSource), profile, profileSource);
            }

            if (_sharedFile.TryGetProfile("default", out profile))
            {
                return(profile.GetAWSCredentials(_sharedFile), profile, _sharedFile);
            }

            return(default);
コード例 #6
0
        public void TestWriteCompatibilitySAML()
        {
            using (var tester = new NetSDKCredentialsFileTestFixture())
            {
                // write with new NetSDKCredentialsFile
                CredentialProfile profile = CredentialProfileTestHelper.GetCredentialProfile(
                    Guid.NewGuid(), "SAMLProfile", CredentialProfileTestHelper.GetRandomOptions(CredentialProfileType.SAMLRoleUserIdentity));
                tester.ProfileStore.RegisterProfile(profile);

                // TODO do this with the new SAML Endpoint Manager
                ProfileManager.RegisterSAMLEndpoint(profile.Options.EndpointName, new Uri("https://somesamlendpoint/"), null);

                // read with old ProfileManager
                SAMLRoleProfile samlProfile;
                Assert.IsTrue(ProfileManager.TryGetProfile("SAMLProfile", out samlProfile));
                Assert.IsNotNull(samlProfile);
                Assert.AreEqual(profile.Options.EndpointName, samlProfile.EndpointSettings.Name);
                Assert.AreEqual(profile.Options.RoleArn, samlProfile.RoleArn);
                Assert.AreEqual(profile.Options.UserIdentity, samlProfile.UserIdentity);
            }
        }
コード例 #7
0
        public void UpsertKey(string profileName, string key, string value, ConfigSource configSource)
        {
            if (!ConfigKey.IsValid(key))
            {
                throw new ArgumentException($"Not a valid credential key: {key}");
            }
            var credentialProfile = _credentialProfileList.FirstOrDefault(cp => cp.ProfileName.Equals(profileName));

            if (credentialProfile == null)
            {
                credentialProfile = new CredentialProfile()
                {
                    ProfileName = profileName
                };
                _credentialProfileList.Add(credentialProfile);
            }
            credentialProfile.Items[key] = new CredentialItem
            {
                Source = configSource,
                Value  = value
            };
        }
コード例 #8
0
        private static bool ValidCredentialsExistInSharedFile(string profilesLocation, string profileName)
        {
            var credentialsFilePath = StoredProfileCredentials.ResolveSharedCredentialFileLocation(profilesLocation);

            if (!string.IsNullOrEmpty(credentialsFilePath))
            {
                var doLog = false;
                try
                {
                    var file = new SharedCredentialsFile(credentialsFilePath);
                    CredentialProfile profile = null;
                    if (file.TryGetProfile(profileName, out profile) && profile.CanCreateAWSCredentials)
                    {
                        return(true);
                    }
                    else
                    {
                        doLog = true;
                    }
                }
                catch (InvalidDataException)
                {
                    doLog = true;
                }

                if (doLog)
                {
                    var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials));
                    logger.InfoFormat("Credentials file {0} does not contain a valid profile named {1}.", credentialsFilePath, profileName);
                }
            }
            else
            {
                var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials));
                logger.InfoFormat("Credentials file not found {0}.", credentialsFilePath);
            }
            return(false);
        }
コード例 #9
0
        public AwsCredentials GetCredentials()
        {
            var chain    = new CredentialProfileStoreChain();
            var profiles = chain.ListProfiles();
            CredentialProfile profile = profiles.FirstOrDefault();

            if (profile == null)
            {
                return(null);
            }

            var credentials = profile.GetAWSCredentials(chain).GetCredentials();
            var credential  = new AwsCredentials {
                AccessKey = credentials.AccessKey, SecretKey = credentials.SecretKey, Token = credentials.Token
            };

            return(new AwsCredentials
            {
                AccessKey = credential.AccessKey,
                SecretKey = credential.SecretKey,
                Token = credential.Token
            });
        }
コード例 #10
0
        private static AWSCredentials GetAwsCredentials()
        {
            var isLocal = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"));

            Log.LogInformation($"is local: {isLocal}");
            var options = new CredentialProfileOptions
            {
                AccessKey = Environment.GetEnvironmentVariable(isLocal ? "PlainUsername" : "UsernameFromKeyVault", EnvironmentVariableTarget.Process),
                SecretKey = Environment.GetEnvironmentVariable(isLocal ? "PlainPassword" : "PasswordFromKeyVault", EnvironmentVariableTarget.Process)
            };
            var profile = new CredentialProfile("s3_reader", options);

            profile.Region = RegionEndpoint.EUCentral1;
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);

            Log.LogInformation($"Calling GetAWSCredentials for profile '{profile.Name}', AccessKey '{profile.Options.AccessKey}'");
            AWSCredentials awsCredentials = AWSCredentialsFactory.GetAWSCredentials(profile, netSDKFile, true);

            Log.LogInformation("Got AWS Credentials");
            return(awsCredentials);
        }
コード例 #11
0
ファイル: config.cs プロジェクト: akira345/RDS_Log_Downloader
        /// <summary>
        /// プロファイルにキーを保存。
        /// </summary>
        /// <returns>True:成功 False:失敗</returns>
        private bool save_config()
        {
            if (string.IsNullOrEmpty(Txt_AWS_AccessKey.Text) || string.IsNullOrEmpty(Txt_AWS_SecretKey.Text))
            {
                return(false);
            }
            else
            {
                //プロファイル設定に保存
                // 参考:http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html

                var profile_options = new CredentialProfileOptions();
                profile_options.AccessKey = Txt_AWS_AccessKey.Text;
                profile_options.SecretKey = Txt_AWS_SecretKey.Text;

                var profile = new CredentialProfile(this.aws_credential_profile_name, profile_options);
                profile.Region = Amazon.RegionEndpoint.APNortheast1; //東京リージョン
                var netSDKFile = new NetSDKCredentialsFile();
                netSDKFile.RegisterProfile(profile);

                return(true);
            }
        }
コード例 #12
0
        public IActionResult AddAwsProfile(AwsViewModel model)
        {
            if (!ModelState.IsValid)
            {
                StatusMessage = "Invalid input";
                return(RedirectToAction(nameof(AwsSettings)));
            }

            var options = new CredentialProfileOptions
            {
                AccessKey = model.AddProfileViewModel.AccessKey,
                SecretKey = model.AddProfileViewModel.SecretKey
            };
            var profile = new CredentialProfile(model.AddProfileViewModel.ProfileName, options)
            {
                Region = RegionEndpoint.GetBySystemName(model.AddProfileViewModel.Region)
            };
            var sharedCredentialsFile = new SharedCredentialsFile();

            sharedCredentialsFile.RegisterProfile(profile);

            StatusMessage = $"Successful added profile '{model.AddProfileViewModel.ProfileName}'";
            return(RedirectToAction(nameof(AwsSettings)));
        }
コード例 #13
0
        public static CredentialProfile GetCredentialProfile(
            Guid?uniqueKey,
            string profileName,
            CredentialProfileOptions options,
            Dictionary <string, string> properties,
            string defaultConfigurationModeName,
            RegionEndpoint region,
            bool?endpointDiscoveryEnabled,
            RequestRetryMode?retryMode,
            int?maxAttempts)
        {
            var profile = new CredentialProfile(profileName, options)
            {
                DefaultConfigurationModeName = defaultConfigurationModeName,
                Region = region,
                EndpointDiscoveryEnabled = endpointDiscoveryEnabled,
                RetryMode   = retryMode,
                MaxAttempts = maxAttempts
            };

            CredentialProfileUtils.SetUniqueKey(profile, uniqueKey);
            ReflectionHelpers.Invoke(profile, "Properties", properties);
            return(profile);
        }
コード例 #14
0
        public Task <InvokeResult> InitAsync(DataStream stream)
        {
            var options = new CredentialProfileOptions
            {
                AccessKey = stream.AwsAccessKey,
                SecretKey = stream.AwsSecretKey
            };

            var profile    = new CredentialProfile("basic_profile", options);
            var netSDKFile = new NetSDKCredentialsFile();
            var region     = Amazon.RegionEndpoint.GetBySystemName(stream.AwsRegion);

            var creds = AWSCredentialsFactory.GetAWSCredentials(profile, netSDKFile);

            _connection = new AwsHttpConnection(creds, region);
            _stream     = stream;

            var pool   = new SingleNodeConnectionPool(new Uri(stream.ElasticSearchDomainName));
            var config = new ConnectionSettings(pool, _connection);

            _client = new ElasticClient(config);

            return(Task <InvokeResult> .FromResult(InvokeResult.Success));
        }
コード例 #15
0
 public static Dictionary <string, string> GetProperties(CredentialProfile profile)
 {
     return(profile.Properties);
 }
コード例 #16
0
 public static bool TryGetProfile(string name, string profileLocation, out CredentialProfile profile)
 {
     return(new CredentialProfileStoreChain(profileLocation).TryGetProfile(name, out profile));
 }
コード例 #17
0
        /// <summary>
        /// WAVEファイルを生成する
        /// </summary>
        /// <param name="textToSpeak">
        /// Text to Speak</param>
        /// <param name="wave">
        /// WAVEファイルのパス</param>
        private void CreateWave(
            string textToSpeak,
            string wave)
        {
            var config   = Settings.Default.PollySettings;
            var endpoint = config.Endpoint;
            var chain    = new CredentialProfileStoreChain();

            var hash        = (config.Region + config.AccessKey + config.SecretKey).GetHashCode().ToString("X4");
            var profileName = $"polly_profile_{hash}";

            AWSCredentials awsCredentials;

            if (!chain.TryGetAWSCredentials(
                    profileName,
                    out awsCredentials))
            {
                var options = new CredentialProfileOptions
                {
                    AccessKey = config.AccessKey,
                    SecretKey = config.SecretKey,
                };

                var profile = new CredentialProfile(profileName, options);
                profile.Region = endpoint;

                chain.RegisterProfile(profile);

                chain.TryGetAWSCredentials(
                    profileName,
                    out awsCredentials);
            }

            if (awsCredentials == null)
            {
                return;
            }

            using (var pc = new AmazonPollyClient(
                       awsCredentials,
                       endpoint))
            {
                var ssml =
                    $@"<speak><prosody volume=""{config.Volume.ToXML()}"" rate=""{config.Rate.ToXML()}"" pitch=""{config.Pitch.ToXML()}"">{textToSpeak}</prosody></speak>";

                var req = new SynthesizeSpeechRequest();
                req.TextType     = TextType.Ssml;
                req.Text         = ssml;
                req.OutputFormat = OutputFormat.Mp3;
                req.VoiceId      = config.Voice;

                var res = pc.SynthesizeSpeech(req);

                using (var fs = new FileStream(wave, FileMode.Create, FileAccess.Write))
                {
                    res.AudioStream.CopyTo(fs);
                    fs.Flush();
                    fs.Close();
                }
            }
        }
コード例 #18
0
 public static bool IsCallbackRequired(CredentialProfile profile)
 {
     return(profile.IsCallbackRequired);
 }
コード例 #19
0
 public static CredentialProfileType?GetProfileType(CredentialProfile profile)
 {
     return(profile.ProfileType);
 }
コード例 #20
0
 public static void SetUniqueKey(CredentialProfile profile, Guid?uniqueKey)
 {
     profile.UniqueKey = uniqueKey;
 }
コード例 #21
0
 public static String GetUniqueKey(CredentialProfile profile)
 {
     return(profile.UniqueKey.HasValue ? profile.UniqueKey.Value.ToString("D") : null);
 }
コード例 #22
0
        static void Main(string[] args)
        {
            const float MIN_CONFIDENCE = 90F;

            try
            {
                string[] imagesList = GetListOfImages();
                if (imagesList == null || imagesList.Length == 0)
                {
                    Console.WriteLine("No images found in the Images folder");
                    return;
                }

                // Constructs a SharedCredentialsFile object from the default credentials file.
                SharedCredentialsFile sharedCredentialsFile = new SharedCredentialsFile();

                // Get the [default] profile from the credentials file.
                CredentialProfile defaultProfile = GetDefaultProfile(sharedCredentialsFile);

                if (defaultProfile != null)
                {
                    // Get the credentials (access key, secret access key, etc.)
                    AWSCredentials credentials = AWSCredentialsFactory.GetAWSCredentials(defaultProfile, new SharedCredentialsFile());

                    AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(credentials, RegionEndpoint.USEast1);

                    CompareFacesRequest detectFacesRequest = new CompareFacesRequest()
                    {
                        SourceImage = GetImage(@"C:\Temp\TomCruise1.jpg"),
                        TargetImage = GetImage(@"C:\Temp\TomCruise2.jpg")
                    };

                    CompareFacesResponse     response = rekognitionClient.CompareFaces(detectFacesRequest);
                    List <CompareFacesMatch> list     = response.FaceMatches;

                    foreach (string filePath in imagesList)
                    {
                        Image image = GetImage(filePath);
                        if (image == null)
                        {
                            continue;
                        }

                        DetectLabelsRequest detectLabelsRequest = new DetectLabelsRequest()
                        {
                            Image         = image,
                            MinConfidence = MIN_CONFIDENCE,
                        };

                        DetectLabelsResponse detectLabelsResponse = rekognitionClient.DetectLabels(detectLabelsRequest);

                        Console.WriteLine("Image: {0}\n", filePath);
                        foreach (Label label in detectLabelsResponse.Labels)
                        {
                            Console.WriteLine("\t{0} ({1})", label.Name, label.Confidence);
                        }

                        Console.WriteLine();
                    }
                }
                else
                {
                    Console.WriteLine("AWS [default] profile not found");
                }
            }
            catch (AmazonRekognitionException ex)
            {
                Console.WriteLine("AWS Rekognition ERROR: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: {0}", ex.Message);
            }

            Console.WriteLine("\nDONE");
            Console.ReadLine();
        }
コード例 #23
0
 internal void SetProfile(CredentialProfile profile)
 {
     this.profile = profile;
     this.InitialS3Client();
 }
コード例 #24
0
        public static async Task <string> GenerateMethodMapJsonAsync(
            string profileName,
            string stackName)
        {
            if (string.IsNullOrEmpty(profileName))
            {
                throw new Exception($"Error: No ProfileName provided");
            }

            if (string.IsNullOrEmpty(stackName))
            {
                throw new Exception($"Error: No StackName provided");
            }

            var sharedCredentialsFile = new SharedCredentialsFile(); // AWS finds the shared credentials store for us
            CredentialProfile profile = null;

            if (!sharedCredentialsFile.TryGetProfile(profileName, out profile))
            {
                throw new Exception($"Error: Aws Profile \"{profileName}\" not found in shared credentials store.");
            }

            AWSCredentials creds = null;

            if (!AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedCredentialsFile, out creds))
            {
                throw new Exception($"Error: Could not get AWS Credentials using specified profile \"{profileName}\".");
            }

            var awsSettings = new AwsSettings();

            if (!awsSettings.ContainsKey("StackName"))
            {
                awsSettings.Add("StackName", stackName);
            }
            else
            {
                awsSettings["StackName"] = stackName;
            }

            // Get Original Template
            var cfClient = new AmazonCloudFormationClient(creds);
            var getTemplateRequestOriginal = new GetTemplateRequest()
            {
                StackName     = stackName,
                TemplateStage = Amazon.CloudFormation.TemplateStage.Original
            };

            var templateReponse = cfClient.GetTemplateAsync(getTemplateRequestOriginal).GetAwaiter().GetResult();
            //var templateBodyIndex = templateReponse.StagesAvailable.IndexOf("Original");
            var templateBody = templateReponse.TemplateBody; // Original is in yaml form
            //var tmplYaml = new StringReader(new YamlDotNet.Serialization.SerializerBuilder().Build().Serialize(templateBody));
            var tmplYaml     = new StringReader(templateBody);
            var templYamlObj = new YamlDotNet.Serialization.DeserializerBuilder().Build().Deserialize(tmplYaml);

            templateBody = new YamlDotNet.Serialization.SerializerBuilder().JsonCompatible().Build().Serialize(templYamlObj);
            var jTemplateObjOriginal = JObject.Parse(templateBody);

            // Get all Stack Resources
            string nextToken      = null;
            bool   foundResources = false;
            var    methodMap      = new Dictionary <string, string>();

            do
            {
                var listStackResourcesRequest = new ListStackResourcesRequest()
                {
                    StackName = stackName, NextToken = nextToken
                };
                var listStackResourcesResponse = await cfClient.ListStackResourcesAsync(listStackResourcesRequest);

                nextToken = listStackResourcesResponse.NextToken;

                foreach (var resource in listStackResourcesResponse.StackResourceSummaries)
                {
                    switch (resource.ResourceType)
                    {
                    case "AWS::Lambda::Function":
                        foundResources = true;
                        var funcName     = resource.LogicalResourceId;
                        var lambdaEvents = jTemplateObjOriginal["Resources"][funcName]["Properties"]["Events"].Children();
                        foreach (JToken le in lambdaEvents)
                        {
                            var jObject = new JObject(le);
                            var name    = jObject.First.First.Path;
                            var type    = jObject[name]["Type"].ToString();
                            var apiId   = string.Empty;

                            if (type.Equals("HttpApi"))
                            {
                                apiId = jObject[name]["Properties"]["ApiId"]["Ref"].ToString();
                            }

                            else if (type.Equals("Api"))
                            {
                                apiId = jObject[name]["Properties"]["RestApiId"]["Ref"].ToString();
                            }

                            if (!string.IsNullOrEmpty(apiId))
                            {
                                methodMap.Add(name + "Async", apiId);
                            }
                        }
                        break;
                    }
                }
            } while (nextToken != null);

            if (!foundResources)
            {
                throw new Exception($"Error: No Lambda resources found for specified stack.");
            }

            var result = $"{{\"MethodMap\": {Newtonsoft.Json.JsonConvert.SerializeObject(methodMap, Newtonsoft.Json.Formatting.Indented)}}}";

            return(result);
        }
コード例 #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Get the environment
            IServiceProvider    serviceProvider = services.BuildServiceProvider();
            IHostingEnvironment env             = serviceProvider.GetService <IHostingEnvironment>();

            services.AddOptions();

            services.Configure <Configurations.Authentication>(Configuration.GetSection("Authentication"));

            if (!bool.TryParse(Configuration["Authentication:DisableAuthentication"], out bool disableAuth))
            {
                disableAuth = false;
            }

            // Allow anonymous if the disable authentication setting is set
            if (disableAuth)
            {
                services.AddMvc(opts =>
                {
                    opts.Filters.Add(new AllowAnonymousFilter());
                    opts.Filters.Add(new ValidateModelStateFilter());
                });
            }
            else
            {
                services.AddMvc(opts =>
                {
                    opts.Filters.Add(new ValidateModelStateFilter());
                });
            }

            // For development purposes only. Allows the frontend to be served
            // from a different domain.
            services.AddCors(o => o.AddPolicy("AllowAllOrigins", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            // Setup the database context
            services.AddDbContext <DatabaseContext>(options =>
            {
                if (env.IsDevelopment())
                {
                    options.UseSqlite(Configuration.GetConnectionString("LocalDatabase"));
                }
                else
                {
                    //var connection = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb");
                    var connection = "database=localdb;server=127.0.0.1;port=50638;user=azure;password=6#vWHD_$";
                    options.UseMySQL(connection);
                }
            });

            // Setting up Auth0 authentication
            string domain = $"https://{Configuration["Auth0:Domain"]}/";

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Authority = domain;
                options.Audience  = Configuration["Auth0:ApiIdentifier"];
            });

            // Setting up the AWS SDK
            var profile = new CredentialProfile("local-test-profile", new CredentialProfileOptions
            {
                AccessKey = Configuration["AWS:AccessKey"],
                SecretKey = Configuration["AWS:SecretKey"],
            });

            profile.Region = RegionEndpoint.USWest1;
            var sharedFile = new SharedCredentialsFile();

            sharedFile.RegisterProfile(profile);
            services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
            services.AddAWSService <IAmazonS3>();
        }
コード例 #26
0
        public static async Task <AwsSettings> GetAwsSettings(string profileName, string stackName)
        {
            if (string.IsNullOrEmpty(profileName))
            {
                throw new Exception($"Error: No ProfileName provided");
            }

            if (string.IsNullOrEmpty(stackName))
            {
                throw new Exception($"Error: No StackName provided");
            }

            var sharedCredentialsFile = new SharedCredentialsFile(); // AWS finds the shared credentials store for us
            CredentialProfile profile = null;

            if (!sharedCredentialsFile.TryGetProfile(profileName, out profile))
            {
                throw new Exception($"Error: Aws Profile \"{profileName}\" not found in shared credentials store.");
            }

            AWSCredentials creds = null;

            if (!AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedCredentialsFile, out creds))
            {
                throw new Exception($"Error: Could not get AWS Credentials using specified profile \"{profileName}\".");
            }

            var awsSettings = new AwsSettings();

            awsSettings["StackName"] = stackName;

            // Get Original Template
            AmazonCloudFormationClient cfClient = null;
            GetTemplateRequest         getTemplateRequestOriginal = null;

            try
            {
                // Note the need to extract region from the profile!
                cfClient = new AmazonCloudFormationClient(creds, profile.Region);
                getTemplateRequestOriginal = new GetTemplateRequest()
                {
                    StackName     = stackName,
                    TemplateStage = Amazon.CloudFormation.TemplateStage.Original
                };
            }
            catch (Exception ex)
            {
                throw new Exception($"Could not create AmazonCloudFormationClient");
            }

            var templateReponse = cfClient.GetTemplateAsync(getTemplateRequestOriginal).GetAwaiter().GetResult();
            //var templateBodyIndex = templateReponse.StagesAvailable.IndexOf("Original");
            var templateBody = templateReponse.TemplateBody; // Original is in yaml form
            //var tmplYaml = new StringReader(new YamlDotNet.Serialization.SerializerBuilder().Build().Serialize(templateBody));
            var tmplYaml     = new StringReader(templateBody);
            var templYamlObj = new YamlDotNet.Serialization.DeserializerBuilder().Build().Deserialize(tmplYaml);

            templateBody = new YamlDotNet.Serialization.SerializerBuilder().JsonCompatible().Build().Serialize(templYamlObj);
            var jTemplateObjOriginal = JObject.Parse(templateBody);


            // Get Processed Template
            var getTemplateRequestProcessed = new GetTemplateRequest()
            {
                StackName     = stackName,
                TemplateStage = Amazon.CloudFormation.TemplateStage.Processed
            };

            templateReponse = cfClient.GetTemplateAsync(getTemplateRequestProcessed).GetAwaiter().GetResult();
            //var templateBodyIndex = templateReponse.StagesAvailable.IndexOf("Original");
            templateBody = templateReponse.TemplateBody;
            var jTemplateObjProcessed = JObject.Parse(templateBody);

            // Get Stack Resources - note: this call only returns the first 100 resources.
            // We are calling it to get the StackId
            var describeStackResourcesRequest = new DescribeStackResourcesRequest()
            {
                StackName = stackName
            };
            var describeStackResourcesResponse = await cfClient.DescribeStackResourcesAsync(describeStackResourcesRequest);

            if (describeStackResourcesResponse.StackResources.Count == 0)
            {
                throw new Exception($"Error: No resources found for specified stack.");
            }

            // Extract region from StackId ARN -- "arn:aws:cloudformation:us-east-1:..."
            var stackIdParts = describeStackResourcesResponse.StackResources[0].StackId.Split(':');


            var region = stackIdParts[3];

            awsSettings["Region"] = region;

            // Get all stack resources - paginated
            // The the ListStackResourcesResponse does not contain the StackId.
            string nextToken     = null;
            string apiName       = null;
            int    resourceCount = 0;
            var    apiGateways   = new Dictionary <string, AwsSettings.Api>();

            awsSettings["ApiGateways"] = apiGateways;
            do
            {
                var listStackResourcesRequest = new ListStackResourcesRequest()
                {
                    StackName = stackName, NextToken = nextToken
                };
                var listStackResourcesResponse = await cfClient.ListStackResourcesAsync(listStackResourcesRequest);

                nextToken = listStackResourcesResponse.NextToken;

                foreach (var resource in listStackResourcesResponse.StackResourceSummaries)
                {
                    resourceCount++;
                    switch (resource.ResourceType)
                    {
                    case "AWS::Cognito::UserPool":
                    case "AWS::Cognito::IdentityPool":
                    case "AWS::Cognito::UserPoolClient":
                        awsSettings[resource.LogicalResourceId] = resource.PhysicalResourceId;
                        break;

                    case "AWS::ApiGatewayV2::Api":
                        var httpApi = new AwsSettings.Api();
                        apiGateways.Add(resource.LogicalResourceId, httpApi);
                        httpApi.Id   = resource.PhysicalResourceId;
                        httpApi.Type = "HttpApi";
                        apiName      = resource.LogicalResourceId;
                        try
                        {
                            var HttpApiSecureAuthType = (string)jTemplateObjProcessed["Resources"][apiName]["Properties"]["Body"]["components"]["securitySchemes"]["OpenIdAuthorizer"]["type"];
                            if (HttpApiSecureAuthType.Equals("oauth2"))
                            {
                                httpApi.SecurityLevel = AwsSettings.SecurityLevel.JWT;
                            }
                            else
                            {
                                httpApi.SecurityLevel = AwsSettings.SecurityLevel.None;
                            }
                        }
                        catch
                        {
                            httpApi.SecurityLevel = AwsSettings.SecurityLevel.None;
                        }
                        httpApi.Stage = (string)jTemplateObjOriginal["Resources"][apiName]["Properties"]["StageName"];
                        break;

                    case "AWS::ApiGateway::RestApi":
                        var restApi = new AwsSettings.Api();
                        apiGateways.Add(resource.LogicalResourceId, restApi);
                        restApi.Id   = resource.PhysicalResourceId;
                        restApi.Type = "Api";
                        apiName      = resource.LogicalResourceId;
                        try
                        {
                            var apiAuthSecurityType = (string)jTemplateObjProcessed["Resources"][apiName]["Properties"]["Body"]["securityDefinitions"]["AWS_IAM"]["x-amazon-apigateway-authtype"];
                            if (apiAuthSecurityType.Equals("awsSigv4"))
                            {
                                restApi.SecurityLevel = AwsSettings.SecurityLevel.AwsSignatureVersion4;
                            }
                            else
                            {
                                restApi.SecurityLevel = AwsSettings.SecurityLevel.None;
                            }
                        }
                        catch
                        {
                            restApi.SecurityLevel = AwsSettings.SecurityLevel.None;
                        }
                        restApi.Stage = (string)jTemplateObjOriginal["Resources"][apiName]["Properties"]["StageName"];
                        break;
                    }
                }
            } while (nextToken != null);

            if (resourceCount == 0)
            {
                throw new Exception($"Error: No resources found for specified stack.");
            }

            return(awsSettings);
        }
コード例 #27
0
    public static void Install()
    {
        MigrateProfile();

        // Use command line filename for credentials (*.csv file). As many as you like can be specified, only the first one found and valid will be used.
        string[] args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length - 1; i++)
        {
            if (args[i] != "--credentials")
            {
                continue;
            }

            Debug.Log(":) LOADING CREDENTIALS STARTED. Install(): --credentials qualifier detected." + Environment.NewLine);

            if (!File.Exists(args[i + 1]))
            {
                Debug.Log(":( LOADING CREDENTIALS FAILED. Install(): Specified credentials file does not exist." + Environment.NewLine);
                continue;
            }

            string[] lines = File.ReadAllLines(args[i + 1]);
            if (lines.Length != 2)
            {
                Debug.Log(":( LOADING CREDENTIALS FAILED. Install(): Specified credentials file contains more or less than one set of credentials." + Environment.NewLine);
                continue;
            }

            string accessKey = "AKIAY5N2GQYNG2HELGPH";
            string secretKey = "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";
            // string[] headers = lines[0].Split(',');
            // string[] credentials = lines[1].Split(',');
            // for (int idx = 0; idx < headers.Length; idx++)
            // {
            //     if (headers[idx] == "Access key ID") accessKey = credentials[idx];
            //     if (headers[idx] == "Secret access key") secretKey = credentials[idx];
            // }

            // Check Access Key
            string pattern1 = @"^[A-Z0-9]{20}$";
            Match  m1       = Regex.Match(accessKey, pattern1);
            if (!m1.Success)
            {
                Debug.Log(":( LOADING CREDENTIALS FAILED. Install(): Specified credentials file contains invalid access key or no access key." + Environment.NewLine);
                continue;
            }

            // Check Secret Key
            string pattern2 = @"^[A-Za-z0-9/+=]{40}$";
            Match  m2       = Regex.Match(secretKey, pattern2);
            if (!m2.Success)
            {
                Debug.Log(":( LOADING CREDENTIALS FAILED. Install(): Specified credentials file contains invalid secret key or no secret key." + Environment.NewLine);
                continue;
            }

            var options = new CredentialProfileOptions
            {
                AccessKey = accessKey,
                SecretKey = secretKey
            };
            var profile = new CredentialProfile(profileName, options);
            new SharedCredentialsFile().RegisterProfile(profile);
            Debug.Log(":) PROFILE REGISTERED SUCCESSFULLY IN SHARED CREDENTIALS FILE." + Environment.NewLine);
            break;
        }
    }
コード例 #28
0
 public static void SetProperty(CredentialProfile profile, string key, string value)
 {
     profile.Properties[key] = value;
 }
コード例 #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //signalR
            services.AddSignalR();

            // Add framework services.
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();
            services.AddMvc();
            services.AddCors(options => options.AddPolicy("CorsPolicy",
                                                          builder =>
            {
                builder.AllowAnyMethod().AllowAnyHeader()
                .WithOrigins("http://localhost:4200")
                .AllowCredentials();
            }));
            services.AddSingleton <IConfiguration>(Configuration);

            //JWT
            var AppSetting = new AppSetting();

            Configuration.GetSection("AppSetting").Bind(AppSetting);
            var secretKey = AppSetting.secretKey;
            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(secretKey)),

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = AppSetting.Issuer,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = AppSetting.Audience,

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = tokenValidationParameters;
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        if (!string.IsNullOrEmpty(accessToken) &&
                            (context.HttpContext.WebSockets.IsWebSocketRequest || context.Request.Headers["Accept"] == "text/event-stream"))
                        {
                            context.Token = context.Request.Query["access_token"];
                        }
                        return(Task.CompletedTask);
                    }
                };
            });


            //AWS Profile
            var AWS_keys = new AWS_keys();

            Configuration.GetSection("AWS").Bind(AWS_keys);
            var aws_profile = AWS_keys.Profile;
            var keys        = new CredentialProfileOptions
            {
                AccessKey = AWS_keys.AWSAccessKey,
                SecretKey = AWS_keys.AWSSecretKey
            };
            var profile    = new CredentialProfile(aws_profile, keys);
            var sharedFile = new SharedCredentialsFile();

            sharedFile.RegisterProfile(profile);

            IAmazonSimpleEmailService client = Configuration.GetAWSOptions().CreateServiceClient <IAmazonSimpleEmailService>();

            services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
            services.AddAWSService <IAmazonSimpleEmailService>();

            IAmazonS3 s3Client = Configuration.GetAWSOptions().CreateServiceClient <IAmazonS3>();

            services.AddAWSService <IAmazonS3>();



            return(services.BuildServiceProvider());
        }
コード例 #30
0
 public bool TryGetProfile(string profileName, out CredentialProfile profile)
 {
     return(Profiles.TryGetValue(profileName, out profile));
 }