Exemplo n.º 1
0
        public async Task <bool> Exists()
        {
            CredentialProfileOptions options = new CredentialProfileOptions();

            Settings settings = Settings.Load();

            options.AccessKey = settings.DBKey;
            options.SecretKey = settings.DBSecret;

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

            profile.Region = RegionEndpoint.APSoutheast2;

            SharedCredentialsFile sharedFile = new SharedCredentialsFile();

            sharedFile.RegisterProfile(profile);

            AmazonDynamoDBConfig dbConfig = new AmazonDynamoDBConfig();

            this.client = new AmazonDynamoDBClient(dbConfig);

            ListTablesResponse listTablesResponse = await this.client.ListTablesAsync();

            return(listTablesResponse.TableNames.Contains(this.InternalName));
        }
Exemplo n.º 2
0
        public async Task Connect()
        {
            CredentialProfileOptions options = new CredentialProfileOptions();

            Settings settings = Settings.Load();

            options.AccessKey = settings.DBKey;
            options.SecretKey = settings.DBSecret;

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

            profile.Region = RegionEndpoint.APSoutheast2;

            SharedCredentialsFile sharedFile = new SharedCredentialsFile();

            sharedFile.RegisterProfile(profile);

            AmazonDynamoDBConfig dbConfig = new AmazonDynamoDBConfig();

            this.client = new AmazonDynamoDBClient(dbConfig);

            await this.EnsureTable();

            this.context = new DynamoDBContext(this.client);

            foreach (JsonConverter converter in Serializer.Options.Converters)
            {
                PropertyInfo prop = converter.GetType().GetProperty("TypeToConvert", BindingFlags.Instance | BindingFlags.NonPublic);

                if (prop == null)
                {
                    throw new Exception("Failed to get target type of json converter: " + converter);
                }

                Type?targetType = prop.GetValue(converter) as Type;

                if (targetType == null)
                {
                    throw new Exception("Failed to get target type of json converter: " + converter);
                }

                this.context.ConverterCache.Add(targetType, new JsonProperty(targetType));
            }

            try
            {
                await this.client.ListTablesAsync();
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to connect to database: " + ex.Message, ex);
            }

            this.operationConfig = new DynamoDBOperationConfig();
            this.operationConfig.OverrideTableName = this.InternalName;
        }
        public async Task <IActionResult> RegisterProfile([FromBody] AWSProfileCredentials aWSCredentials)
        {
            try
            {
                using (IAmazonS3 amazonS3 = new AmazonS3Client(aWSCredentials.AccessKey, aWSCredentials.SecretKey, RegionEndpoint.USEast1))
                {
                    try
                    {
                        var s3Resource = await amazonS3.ListBucketsAsync();
                    }
                    catch (Amazon.S3.AmazonS3Exception ex)
                    {
                        if (ex.ErrorCode.Equals("InvalidAccessKeyId") || ex.ErrorCode.Equals("SignatureDoesNotMatch"))
                        {
                            return(BadRequest(new { Message = "Invalid access or secret key" }));
                        }
                    }
                }
                var netSDKFile = new SharedCredentialsFile();
                CredentialProfile basicProfile;
                if (netSDKFile.TryGetProfile(aWSCredentials.ProfileName, out basicProfile))
                {
                    netSDKFile.UnregisterProfile(aWSCredentials.ProfileName);
                    CredentialProfileOptions options = new CredentialProfileOptions()
                    {
                        AccessKey = aWSCredentials.AccessKey,
                        SecretKey = aWSCredentials.SecretKey
                    };
                    var profile = new CredentialProfile(aWSCredentials.ProfileName, options);
                    netSDKFile = new SharedCredentialsFile();
                    netSDKFile.RegisterProfile(profile);
                }
                else
                {
                    CredentialProfileOptions options = new CredentialProfileOptions()
                    {
                        AccessKey = aWSCredentials.AccessKey,
                        SecretKey = aWSCredentials.SecretKey
                    };
                    var profile = new CredentialProfile(aWSCredentials.ProfileName, options);
                    //netSDKFile = new SharedCredentialsFile(Directory.GetCurrentDirectory()+ @"\Credentials");
                    netSDKFile = new SharedCredentialsFile();
                    netSDKFile.RegisterProfile(profile);
                }


                return(Ok("Registered"));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message + ex.StackTrace));
            }
        }
Exemplo n.º 4
0
        private void InitAwsCredetialsFile()
        {
            var options = new CredentialProfileOptions()
            {
                AccessKey = "",
                SecretKey = ""
            };
            var profile = new CredentialProfile("vilab_profile", options)
            {
                Region = RegionEndpoint.EUCentral1
            };
            var sharedFile = new SharedCredentialsFile();

            sharedFile.RegisterProfile(profile);
        }
Exemplo n.º 5
0
        public TurkSurvey(AppSettings appSettings)
        {
            _appSettings = appSettings;


            var options = new CredentialProfileOptions
            {
                AccessKey = _appSettings.awsAccessKey,
                SecretKey = _appSettings.awsSecret
            };
            var profile = new CredentialProfile("basic_profile", options);

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

            sharedFile.RegisterProfile(profile);
        }
Exemplo n.º 6
0
    public static void MigrateProfile()
    {
        // Credential profile used to be stored in .net sdk credentials store.
        // Shared credentials file is more modern. Migrate old profile if needed.
        // Shows good form for profile management
        CredentialProfile profile;
        var scf = new SharedCredentialsFile();

        if (!scf.TryGetProfile(profileName, out _))
        {
            var nscf = new NetSDKCredentialsFile();
            if (nscf.TryGetProfile(profileName, out profile))
            {
                scf.RegisterProfile(profile);
                nscf.UnregisterProfile(profileName);
            }
        }
    }
        static void SetProfileOnDeploy()
        {
            String profileName = ConfigurationManager.AppSettings["AWSProfileName"];
            String accessKeyId = ConfigurationManager.AppSettings["OctopusAccessIdToken"];
            String accessKey   = ConfigurationManager.AppSettings["OctopusAccessKeyToken"];

            CredentialProfileOptions options = new CredentialProfileOptions
            {
                AccessKey = accessKeyId,
                SecretKey = accessKey
            };
            CredentialProfile profile = new CredentialProfile(profileName, options);

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

            sharedFile.RegisterProfile(profile);
        }
        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();
        }
Exemplo n.º 9
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);
        }
Exemplo n.º 10
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)));
        }
Exemplo n.º 11
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());
        }
Exemplo n.º 12
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>();
        }