Ejemplo n.º 1
0
        /// <summary>Gets the authentication token.</summary>
        /// <returns></returns>
        private async Task <string> GetAuthToken()
        {
            bool.TryParse(Environment.GetEnvironmentVariable(Constants.KeyVaultEnabled), out bool isKeyVaultEnabled);
            if (isKeyVaultEnabled)
            {
                ClientId = await KeyVaultHelper.GetKeyValueAsync(Constants.ClientId);

                ClientSecret = await KeyVaultHelper.GetKeyValueAsync(Constants.ClientSecret);
            }
            else
            {
                ClientId     = Environment.GetEnvironmentVariable(Constants.ClientId);
                ClientSecret = Environment.GetEnvironmentVariable(Constants.ClientSecret);
            }

            string ResourceId = Environment.GetEnvironmentVariable(Constants.ResourceId);

            var authContext = CreateAuthenticationContext();

            try
            {
                log.LogInformation(Constants.OAuthBearerTokenGenerationStarted);
                ClientCredential clientCredential = new ClientCredential(ClientId, ClientSecret);
                var token = await authContext.AcquireTokenAsync(ResourceId, clientCredential);

                log.LogInformation(Constants.OAuthBearerTokenGenerationCompleted);
                return(token.AccessToken);
            }
            catch (Exception ex)
            {
                log.LogInformation(Constants.OAuthBearerTokenGenerationFailed);
                log.LogInformation(ex.InnerException.ToString());
                throw ex;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// ProcessRecord
        /// </summary>
        protected override void ProcessRecord()
        {
            Data.KeyVault KeyVault = KeyVaultHelper.GetItemThrow(null, VaultName, true);

            if (!(String.IsNullOrEmpty(KeyVault.Thumbprint)))
            {
                WriteError(
                    (new PSAdminException(PSAdminExceptionType.ParameterDefined, String.Format("in KeyVault '{0}' with the name of '{1}'", VaultName, Thumbprint))).GetErrorRecord()
                    );
                return;
            }

            Data.KeyVaultCertificate[] SearchCertificate = KeyVaultCertificateHelper.GetItemsThrow(null, KeyVault.VaultName, null, Thumbprint, null, false, true);

            X509Certificate2 x509 = (X509Certificate2)SearchCertificate[0].Certificate;

            if ((x509.HasPrivateKey == false) || (x509.PrivateKey == null))
            {
                WriteError(
                    (new PSAdminException(PSAdminExceptionType.CertificatePrivateKey, Thumbprint)).GetErrorRecord()
                    );
                return;
            }

            Hashtable filter = new Hashtable {
                { "Id", KeyVault.Id },
                { "VaultName", KeyVault.VaultName },
            };
            Hashtable row = new Hashtable {
                { "Thumbprint", x509.Thumbprint },
                { "VaultKey", ((RSACryptoServiceProvider)x509.PublicKey.Key).Encrypt(KeyVault.VaultKey, true) }
            };

            bool issuccessful = KeyVaultHelper.SetItemsThrow(row, filter, true);
        }
Ejemplo n.º 3
0
        public Startup(IWebHostEnvironment env, IConfiguration configuration)
        {
            Configuration = configuration;

            if (env.IsDevelopment())
            {
                // 開発:UserSecretsから取得
                Configuration[Constants.AppSettingPath.Secrets.ClientSecret] =
                    configuration.GetValue <string>(Constants.UserSecrets.ClientSecret);

                Configuration[Constants.AppSettingPath.Secrets.DbConnectionString] =
                    configuration.GetConnectionString(Constants.UserSecrets.ConnectionStrings.Database);

                Configuration[Constants.AppSettingPath.Secrets.SlackAppToken] =
                    configuration.GetValue <string>(Constants.UserSecrets.SlackAppToken);
            }
            else
            {
                // 開発以外:appsettings.jsonの値でKeyVaultを参照しシークレットを取得して上書き
                Configuration[Constants.AppSettingPath.Secrets.ClientSecret] =
                    KeyVaultHelper.GetSecretFromKeyVaultAsync(Configuration[Constants.AppSettingPath.Secrets.ClientSecret]).Result.Result;

                Configuration[Constants.AppSettingPath.Secrets.DbConnectionString] =
                    KeyVaultHelper.GetSecretFromKeyVaultAsync(Configuration[Constants.AppSettingPath.Secrets.DbConnectionString]).Result.Result;

                Configuration[Constants.AppSettingPath.Secrets.SlackAppToken] =
                    KeyVaultHelper.GetSecretFromKeyVaultAsync(Configuration[Constants.AppSettingPath.Secrets.SlackAppToken]).Result.Result;
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Process Record
        /// </summary>
        protected override void ProcessRecord()
        {
            Data.KeyVault KeyVault = KeyVaultHelper.GetItemThrow(null, VaultName, true);

            Data.KeyVaultCertificate[] SearchCertificate = KeyVaultCertificateHelper.GetItemsThrow(null, VaultName, Name, null, null, false, true);

            // Note: This will only ever return one item
            foreach (Data.KeyVaultCertificate Certificate in SearchCertificate)
            {
                X509Certificate2 x509 = (X509Certificate2)Certificate.Certificate;
                byte[]           CertificateByteArray = x509.Export(X509ContentType.Pkcs12, Password);
                x509.Dispose();
                switch (ParameterSetName)
                {
                case ImportFromFileParameterSetName:
                    File.WriteAllBytes(FileName, CertificateByteArray);
                    break;

                case ImportFromStringParameterSetName:
                    WriteObject(
                        Convert.ToBase64String(CertificateByteArray)
                        );
                    break;

                default:
                    WriteError(
                        (new PSAdminException(PSAdminExceptionType.ParameterSetNotFound, Name, "Name")).GetErrorRecord()
                        );
                    return;
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Run the app
        /// </summary>
        /// <param name="keyvaultName">Keyvault Name</param>
        /// <param name="authType">Authentication Type</param>
        /// <param name="dryRun">Dry Run flag</param>
        /// <returns></returns>
        public static async Task <int> RunApp(string keyvaultName, AuthenticationType authType, LogLevel logLevel, bool dryRun)
        {
            // validate keyvaultName and convert to URL
            if (!KeyVaultHelper.BuildKeyVaultConnectionString(keyvaultName, out string kvUrl))
            {
                return(-1);
            }

            try
            {
                // setup ctl c handler
                ctCancel = SetupCtlCHandler();

                AppLogLevel = logLevel;

                // build the host
                host = await BuildHost(kvUrl, authType).ConfigureAwait(false);

                if (host == null)
                {
                    return(-1);
                }

                // don't start the web server
                if (dryRun)
                {
                    return(DoDryRun(kvUrl, authType));
                }

                // log startup messages
                LogStartup();

                // start the webserver
                var w = host.RunAsync();

                // this doesn't return except on ctl-c
                await w.ConfigureAwait(false);

                // use this line instead if you want to re-read the Cosmos connection info on a timer
                //await RunKeyRotationCheck(ctCancel, Constants.KeyVaultChangeCheckSeconds).ConfigureAwait(false);

                // if not cancelled, app exit -1
                return(ctCancel.IsCancellationRequested ? 0 : -1);
            }

            catch (Exception ex)
            {
                // end app on error
                if (logger != null)
                {
                    logger.LogError($"Exception: {ex}");
                }
                else
                {
                    Console.WriteLine($"{ex}\nError in Main() {ex.Message}");
                }

                return(-1);
            }
        }
Ejemplo n.º 6
0
        public async System.Threading.Tasks.Task TestMethod1Async()
        {
            KeyVaultHelper helper = new KeyVaultHelper();

            EncrptHandler e = new EncrptHandler();

            string    ed          = e.EncryptData("gaurav");
            string    keyVaulturl = "https://gaurav-1.vault.azure.net/";
            string    keyname     = "gaurav-key1";
            KeyBundle x           = await helper.CreateKey(keyVaulturl, keyname);

            byte[] wrapped_key = await helper.WrapKey(e.aesM.Key, keyVaulturl, keyname);

            string secretname = "gaurav-secret";

            string value = Convert.ToBase64String(wrapped_key);

            helper.CreateSecretInKeyvaultTostoreWrappedKey(value, keyVaulturl, secretname);
            string wrapped_Aes_key_which_is_stored_in_keyvault = (await helper.GetSecret(keyVaulturl, secretname)).Value;

            Console.WriteLine(wrapped_Aes_key_which_is_stored_in_keyvault);
            //Console.WriteLine("llalla");
            Console.WriteLine(value);
            byte[] wrapped_aes_key_which_is_stored_in_keyvault = Convert.FromBase64String(wrapped_Aes_key_which_is_stored_in_keyvault);

            byte[] aesKey = await helper.UnwrapKey(wrapped_aes_key_which_is_stored_in_keyvault, keyVaulturl, keyname);

            string dd = e.DecryptData(ed, aesKey);

            Assert.AreEqual("gaurav", dd);
            Console.WriteLine(ed);
            Console.WriteLine(dd);
        }
Ejemplo n.º 7
0
        public static async Task <JsonWebKey> GetKeyFromKeyVaultAsync(this string keyName, IKeyVaultHelperSettings settings = null)
        {
            var manager = new KeyVaultHelper(settings ?? KeyVaultHelperSettingsResolver.Current);
            var result  = await manager.GetKeyBundleAsync(keyName);

            return(result.Key);
        }
        public static async Task <X509Certificate2> GetAsync()
        {
            int          retries    = 0;
            const int    maxRetries = 4;
            const string certName   = "JwtCert";

            while (true)
            {
                try
                {
                    /* The next four lines of code show you how to use AppAuthentication library to fetch secrets from your key vault */
                    // Note that for this to work on developer machine, you must install Azure CLI and log in
                    SecretBundle secretBundle = await KeyVaultHelper.GetSecretAsync(certName);

                    return(new X509Certificate2(Convert.FromBase64String(secretBundle.Value)));
                }

                /* If you have throttling errors see this tutorial https://docs.microsoft.com/azure/key-vault/tutorial-net-create-vault-azure-web-app */
                /// <exception cref="KeyVaultErrorException">
                /// Thrown when the operation returned an invalid status code
                /// </exception>
                catch (KeyVaultErrorException keyVaultException)
                {
                    if (retries < maxRetries)
                    {
                        retries++;
                        await Task.Delay(getWaitTime(retries));
                    }
                    else
                    {
                        throw keyVaultException;
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public void FillQueue()
        {
            KeyVaultHelper.LogIntoKeyVault();
            var connectionString = KeyVaultHelper.GetSecret("https://spotify-matchmaker.vault.azure.net/secrets/storage-connection-string/");

            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            // Create the queue client.
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a queue.
            CloudQueue queue = queueClient.GetQueueReference("spotify-queue");

            // Create the queue if it doesn't already exist.
            queue.CreateIfNotExists();

            HashSet <string> partyCodes = new HashSet <string>();

            for (int i = 0; i < 100; i++)
            {
                // Party newParty = MakeRandomParty();
                string randomCode = RandomString(4);

                partyCodes.Add(randomCode);
            }

            // Create a message and add it to the queue.
            CloudQueueMessage message = new CloudQueueMessage("Hello, World");

            queue.AddMessage(message);
        }
Ejemplo n.º 10
0
        public static async Task <string> GetSecretFromKeyVaultAsync(this string secretName, IKeyVaultHelperSettings settings = null)
        {
            var manager = new KeyVaultHelper(settings ?? KeyVaultHelperSettingsResolver.Current);
            var result  = await manager.GetSecretBundleAsync(secretName);

            return(result.Value);
        }
Ejemplo n.º 11
0
        static async Task Main(string[] args)
        {
            var client = new SecretClient(KeyVaultHelper.GetVaultUri(VAULT_NAME), new DefaultAzureCredential());
            var secret = await client.GetSecretAsync(SECRET_NAME);

            Console.WriteLine($"The secret value I retrieved from Key Vault: {secret.Value}!");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Process Record
        /// </summary>
        protected override void ProcessRecord()
        {
            Data.KeyVault[] vaults = KeyVaultHelper.GetItemsThrow(null, VaultName, !Match);

            Data.Computer[] computers = GetPSAdminComputer.Call(Id, VaultName, ComputerName, null, !Match);

            if ((Match == false) && (computers.Length < 1))
            {
                WriteError(
                    (new PSAdminException(PSAdminExceptionType.ItemNotFoundLookup, ComputerName, "ComputerName")).GetErrorRecord()
                    );
                return;
            }

            // Unroll the object
            foreach (Data.Computer computer in computers)
            {
                if (!ShouldProcess(computer.ComputerName, "Remove"))
                {
                    continue;
                }

                bool IsSuccessful = Call(computer.Id, computer.VaultName, computer.ComputerName, !Match);
                if (!IsSuccessful)
                {
                    WriteError(
                        (new PSAdminException(PSAdminExceptionType.RowDelete)).GetErrorRecord()
                        );
                }
            }
        }
Ejemplo n.º 13
0
        public static void Run([QueueTrigger("spotify-queue", Connection = "AzureWebJobsStorage")] string myQueueItem, ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

            // parse the json queue data for party code
            var jObject = JObject.Parse(myQueueItem);
            var jToken  = jObject.GetValue("party_code");

            string partyCode = jToken.ToString();

            KeyVaultHelper.LogIntoKeyVault();
            var connectionString = KeyVaultHelper.GetSecret("https://spotify-matchmaker.vault.azure.net/secrets/storage-connection-string/");

            var table = AzureStorageHelper.GetOrCreateTableAsync("partyCodes", connectionString).Result;

            var accessTokens = AzureStorageHelper.GetParty(partyCode, table).GetAccessTokens();

            log.LogInformation($"Access token for party code: {partyCode}");
            foreach (var token in accessTokens)
            {
                // log.LogInformation($"Access token: {token}");
            }


            //take the party code and go to Azure Cosmos DB to lookup the party

            //grab spotify tokens from Cosmos DB and snoop through their music collections
            ;
        }
Ejemplo n.º 14
0
        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";
            var valueFromKeyVault = KeyVaultHelper.GetValueAsync(Configuration["AuthorizationkeyFromKeyVault"]).GetAwaiter().GetResult();

            ViewData["AuthorizationKey"] = valueFromKeyVault;
            return(View());
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Build the web host
        /// </summary>
        /// <param name="kvUrl">URL of the Key Vault</param>
        /// <param name="authType">MI, CLI, VS</param>
        /// <returns>Web Host ready to run</returns>
        private static async Task <IWebHost> BuildHost(string kvUrl, AuthenticationType authType)
        {
            // create the Key Vault Client
            KeyVaultClient kvClient = await KeyVaultHelper.GetKeyVaultClient(kvUrl, authType, Constants.CosmosDatabase).ConfigureAwait(false);

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

            // build the config
            // we need the key vault values for the DAL
            config = BuildConfig(kvClient, kvUrl);

            // configure the web host builder
            IWebHostBuilder builder = WebHost.CreateDefaultBuilder()
                                      .UseConfiguration(config)
                                      .UseUrls(string.Format(System.Globalization.CultureInfo.InvariantCulture, $"http://*:{Constants.Port}/"))
                                      .UseStartup <Startup>()
                                      .UseShutdownTimeout(TimeSpan.FromSeconds(Constants.GracefulShutdownTimeout))
                                      .ConfigureServices(services =>
            {
                // add the data access layer via DI
                services.AddDal(
                    new Uri(config.GetValue <string>(Constants.CosmosUrl)),
                    config.GetValue <string>(Constants.CosmosKey),
                    config.GetValue <string>(Constants.CosmosDatabase),
                    config.GetValue <string>(Constants.CosmosCollection));

                // add the KeyVaultConnection via DI
                services.AddKeyVaultConnection(kvClient, kvUrl);

                // add IConfigurationRoot
                services.AddSingleton <IConfigurationRoot>(config);
                services.AddKeyRotation();
                services.AddResponseCaching();
            });

            // configure logger based on command line
            builder.ConfigureLogging(logger =>
            {
                logger.ClearProviders();
                logger.AddConsole();

                // if you specify the --log-level option, it will override the appsettings.json options
                // remove any or all of the code below that you don't want to override
                if (App.IsLogLevelSet)
                {
                    logger.AddFilter("Microsoft", AppLogLevel)
                    .AddFilter("System", AppLogLevel)
                    .AddFilter("Default", AppLogLevel)
                    .AddFilter("CSE.Helium", AppLogLevel);
                }
            });

            // build the host
            return(builder.Build());
        }
Ejemplo n.º 16
0
        public override async Task <string> GetSecret(string secretName)
        {
            string token = KeyVaultHelper.getToken();
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            KeyVaultClient            keyVaultClient            = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
            var secret = await keyVaultClient.GetSecretAsync("https://reubenkv.vault.azure.net/secrets/" + secretName);

            return(secret.Value);
        }
Ejemplo n.º 17
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            var client = new SecretClient(KeyVaultHelper.GetVaultUri(VAULT_NAME), new DefaultAzureCredential());
            var secret = (await client.GetSecretAsync(SECRET_NAME)).Value;

            return(new OkObjectResult($"The secret value I retrieved from Key Vault: {secret.Value}!"));
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Process Record
 /// </summary>
 protected override void ProcessRecord()
 {
     Data.KeyVault[] results = KeyVaultHelper.GetItems(Id, VaultName, Exact);
     // Unroll the object
     foreach (Data.KeyVault result in results)
     {
         WriteObject(result);
     }
 }
Ejemplo n.º 19
0
        static async Task Main(string[] args)
        {
            var tokenProvider = new AzureServiceTokenProvider();
            var callback      = new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback);
            var client        = new KeyVaultClient(callback);

            var secret = await client.GetSecretAsync(KeyVaultHelper.GetVaultUrl(VAULT_NAME), SECRET_NAME);

            Console.WriteLine($"The secret value I retrieved from Key Vault: {secret.Value}!");
        }
Ejemplo n.º 20
0
        private static void Init()
        {
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            Console.WriteLine($"Environment: {environment}");

            var builder = new ConfigurationBuilder()
                          .AddJsonFile($"appsettings.{environment}.json", true, true)
                          .AddEnvironmentVariables();

            IConfigurationRoot Configuration = builder.Build();

            // Retrieve configuration from sections
            ApplicationSettings.ConnectionString          = Configuration.GetSection("ApplicationSettings:ConnectionString")?.Value;
            ApplicationSettings.DatabaseId                = Configuration.GetSection("ApplicationSettings:DatabaseId")?.Value;
            ApplicationSettings.UserCollection            = Configuration.GetSection("ApplicationSettings:UserCollection")?.Value;
            ApplicationSettings.RabbitMQUsername          = Configuration.GetSection("ApplicationSettings:RabbitMQUsername")?.Value;
            ApplicationSettings.RabbitMQPassword          = Configuration.GetSection("ApplicationSettings:RabbitMQPassword")?.Value;
            ApplicationSettings.RabbitMQHostname          = Configuration.GetSection("ApplicationSettings:RabbitMQHostname")?.Value;
            ApplicationSettings.RabbitMQPort              = Convert.ToInt16(Configuration.GetSection("ApplicationSettings:RabbitMQPort")?.Value);
            ApplicationSettings.UserRegistrationQueueName = Configuration.GetSection("ApplicationSettings:UserRegistrationQueueName")?.Value;
            ApplicationSettings.KeyVaultCertificateName   = Configuration.GetSection("ApplicationSettings:KeyVaultCertificateName")?.Value;
            ApplicationSettings.KeyVaultClientId          = Configuration.GetSection("ApplicationSettings:KeyVaultClientId")?.Value;
            ApplicationSettings.KeyVaultClientSecret      = Configuration.GetSection("ApplicationSettings:KeyVaultClientSecret")?.Value;
            ApplicationSettings.KeyVaultIdentifier        = Configuration.GetSection("ApplicationSettings:KeyVaultIdentifier")?.Value;
            ApplicationSettings.KeyVaultEncryptionKey     = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value;
            ApplicationSettings.SendGridAPIKey            = Configuration.GetSection("ApplicationSettings:SendGridAPIKey")?.Value;

            mongoDBConnectionInfo = new MongoDBConnectionInfo()
            {
                ConnectionString = ApplicationSettings.ConnectionString,
                DatabaseId       = ApplicationSettings.DatabaseId,
                UserCollection   = ApplicationSettings.UserCollection
            };

            keyVaultConnectionInfo = new KeyVaultConnectionInfo()
            {
                CertificateName    = ApplicationSettings.KeyVaultCertificateName,
                ClientId           = ApplicationSettings.KeyVaultClientId,
                ClientSecret       = ApplicationSettings.KeyVaultClientSecret,
                KeyVaultIdentifier = ApplicationSettings.KeyVaultIdentifier
            };

            using (KeyVaultHelper keyVaultHelper = new KeyVaultHelper(keyVaultConnectionInfo))
            {
                secret = keyVaultHelper.GetVaultKeyAsync(ApplicationSettings.KeyVaultEncryptionKey).Result;
            }

            using (BlockchainHelper blockchainHelper = new BlockchainHelper())
            {
                wordlist = blockchainHelper.ReadMnemonic();
            }
        }
Ejemplo n.º 21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            Settings.AuthorizationKey        = Configuration.GetSection("ApplicationSettings:AuthorizationKey")?.Value;
            Settings.KeyVaultEncryptionKey   = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value;
            Settings.KeyVaultApplicationCode = Configuration.GetSection("ApplicationSettings:KeyVaultApplicationCode")?.Value;

            // Add Application Insights services into service collection
            services.AddApplicationInsightsTelemetry();

            // Add the standard telemetry client
            services.AddSingleton <TelemetryClient, TelemetryClient>();

            // Adding EncryptionKey and ApplicationCode
            using (KeyVaultHelper keyVaultHelper = new KeyVaultHelper(EnvironmentName, ContentRootPath))
            {
                Settings.KeyVaultEncryptionKey = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value;
                EncryptionKey = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultEncryptionKey).Result;

                Settings.KeyVaultApplicationCode = Configuration.GetSection("ApplicationSettings:KeyVaultApplicationCode")?.Value;
                ApplicationCode = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultApplicationCode).Result;
            }

            // Adding Consul hosted service
            using (ConsulHelper consulHelper = new ConsulHelper(EnvironmentName, ContentRootPath))
            {
                consulHelper.Initialize(services, Configuration);
            }

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = "https://BotApp.Luis.Router.Identity",
                    ValidAudience    = "https://BotApp.Luis.Router.Identity",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Settings.AuthorizationKey))
                };
            });

            services.AddCors(o => o.AddPolicy("AllowAllPolicy", options =>
            {
                options.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Process Record
        /// </summary>
        protected override void ProcessRecord()
        {
            String Id = Guid.NewGuid().ToString().Replace("-", "");

            KeyVaultHelper.NewItemThrow(Id, VaultName, Location, VaultURI, SoftDeleteEnabled, Tags);

            if (Passthru)
            {
                Data.KeyVault result = KeyVaultHelper.GetItem(null, VaultName, true);
                WriteObject(result);
            }
        }
Ejemplo n.º 23
0
        public static void Main(string[] args)
        {
            try
            {
                EnvironmentConfig.Initialize();

                TelemetryConfiguration telemetryConfig = new TelemetryConfiguration(
                    EnvironmentConfig.Singleton.AppInsightsInstrumentationKey);
                TelemetryHelper.Initilize(telemetryConfig, SourceName);
            }
            catch (Exception error)
            {
                Console.WriteLine(
                    "UNHANDLED EXCEPTION during initialization before TelemetryClient oculd be created: {0}",
                    error);

                throw;
            }

            try
            {
                _ = EnvironmentConfig.Singleton.TenantId;
                _ = EnvironmentConfig.Singleton.AllowedUsers;

                KeyVaultHelper.Initialize(new Uri(EnvironmentConfig.Singleton.KeyVaultUri), new DefaultAzureCredential());

                using (CosmosClient client =
                           KeyVaultHelper.Singleton.CreateCosmosClientFromKeyVault(
                               EnvironmentConfig.Singleton.MigrationMetadataCosmosAccountName,
                               WebAppUserAgentPrefix,
                               useBulk: false,
                               retryOn429Forever: true))
                {
                    MigrationConfigDal.Initialize(
                        client.GetContainer(
                            EnvironmentConfig.Singleton.MigrationMetadataDatabaseName,
                            EnvironmentConfig.Singleton.MigrationMetadataContainerName),
                        EnvironmentConfig.Singleton.DefaultSourceAccount,
                        EnvironmentConfig.Singleton.DefaultDestinationAccount);

                    CreateHostBuilder(args).Build().Run();
                }
            }
            catch (Exception unhandledException)
            {
                TelemetryHelper.Singleton.LogError(
                    "UNHANDLED EXCEPTION: {0}",
                    unhandledException);

                throw;
            }
        }
        private void CreateCloudStroageHandler()
        {
            bool.TryParse(Environment.GetEnvironmentVariable(Constants.KeyVaultEnabled), out bool isKeyVaultEnabled);
            if (isKeyVaultEnabled)
            {
                storageAccount = CloudStorageAccount.Parse(KeyVaultHelper.GetKeyValueAsync(Constants.StorageContainerConnectionString).Result);
            }
            else
            {
                storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable(Constants.StorageContainerConnectionString));
            }

            EnsureRequiredContainers();
        }
Ejemplo n.º 25
0
        private async Task SendWebPushNotificationAsync(string userId, string notificationType, string notificationId, ITenant tenant, WebPushTemplate webPushTemplate)
        {
            if (webPushTemplate is null)
            {
                throw new Exception($"There is no WebPushTemplate defined for tenant: {tenant.Id} and notification type: {notificationType}");
            }

            // UserId will be a combination of tenantId and userId of that business.
            string airshipUserId = $"{tenant.Id}:{userId}";

            // Fetch the shared airship config url from the tenant
            tenant.Properties.TryGet(Constants.TenantPropertyNames.AirshipKeyVaultUrl, out string airshipKeyVaultUrl);
            if (string.IsNullOrEmpty(airshipKeyVaultUrl))
            {
                throw new Exception($"There is no SharedAirshipConfig defined for tenant: {tenant.Id} and notification type: {notificationType}");
            }

            string?airshipSecretsString = await KeyVaultHelper.GetDeliveryChannelSecretAsync(this.configuration, airshipKeyVaultUrl).ConfigureAwait(false);

            if (string.IsNullOrEmpty(airshipSecretsString))
            {
                throw new Exception("There is no airship delivery channel configuration setup in the keyvault");
            }

            // Convert secret to airship secret model
            Airship airshipSecrets = JsonConvert.DeserializeObject <Airship>(airshipSecretsString);

            var airshipDeliveryChannelObject = new AirshipDeliveryChannel(
                webPushTemplate.Title !,
                webPushTemplate.Body !,
                webPushTemplate.ActionUrl !);

            try
            {
                AirshipWebPushResponse?airshipResponse = await this.SendAirshipNotificationAsync(
                    airshipUserId,
                    airshipDeliveryChannelObject,
                    airshipSecrets).ConfigureAwait(false);

                await this.UpdateNotificationDeliveryStatusAsync(
                    airshipDeliveryChannelObject.ContentType,
                    notificationId,
                    airshipResponse is null?UserNotificationDeliveryStatus.Unknown : UserNotificationDeliveryStatus.NotTracked,
                    tenant).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await this.UpdateNotificationDeliveryStatusAsync(airshipDeliveryChannelObject.ContentType, notificationId, UserNotificationDeliveryStatus.PermanentlyFailed, tenant, ex.Message).ConfigureAwait(false);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Process Record
        /// </summary>
        protected override void ProcessRecord()
        {
            Data.KeyVault[] vaults = KeyVaultHelper.GetItemsThrow(Id, VaultName, !Match);

            // This should always remove item as exact values.
            foreach (Data.KeyVault vault in vaults)
            {
                if (!ShouldProcess(vault.VaultName, "Remove"))
                {
                    continue;
                }
                KeyVaultHelper.RemoveItems(vault.Id, vault.VaultName, true);
            }
        }
Ejemplo n.º 27
0
        private static void Init()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile($"appsettings.json", true, true)
                          .AddEnvironmentVariables();

            IConfigurationRoot Configuration = builder.Build();

            // Retrieve configuration from sections
            Settings.ConnectionString          = Configuration.GetSection("ConnectionString")?.Value;
            Settings.DatabaseId                = Configuration.GetSection("DatabaseId")?.Value;
            Settings.UserCollection            = Configuration.GetSection("UserCollection")?.Value;
            Settings.RabbitMQUsername          = Configuration.GetSection("RabbitMQUsername")?.Value;
            Settings.RabbitMQPassword          = Configuration.GetSection("RabbitMQPassword")?.Value;
            Settings.RabbitMQHostname          = Configuration.GetSection("RabbitMQHostname")?.Value;
            Settings.RabbitMQPort              = Convert.ToInt16(Configuration.GetSection("RabbitMQPort")?.Value);
            Settings.UserRegistrationQueueName = Configuration.GetSection("UserRegistrationQueueName")?.Value;
            Settings.KeyVaultCertificateName   = Configuration.GetSection("KeyVaultCertificateName")?.Value;
            Settings.KeyVaultClientId          = Configuration.GetSection("KeyVaultClientId")?.Value;
            Settings.KeyVaultClientSecret      = Configuration.GetSection("KeyVaultClientSecret")?.Value;
            Settings.KeyVaultIdentifier        = Configuration.GetSection("KeyVaultIdentifier")?.Value;
            Settings.KeyVaultEncryptionKey     = Configuration.GetSection("KeyVaultEncryptionKey")?.Value;
            Settings.SendGridAPIKey            = Configuration.GetSection("SendGridAPIKey")?.Value;

            mongoDBConnectionInfo = new MongoDBConnectionInfo()
            {
                ConnectionString = Settings.ConnectionString,
                DatabaseId       = Settings.DatabaseId,
                UserCollection   = Settings.UserCollection
            };

            keyVaultConnectionInfo = new KeyVaultConnectionInfo()
            {
                CertificateName    = Settings.KeyVaultCertificateName,
                ClientId           = Settings.KeyVaultClientId,
                ClientSecret       = Settings.KeyVaultClientSecret,
                KeyVaultIdentifier = Settings.KeyVaultIdentifier
            };

            using (KeyVaultHelper keyVaultHelper = new KeyVaultHelper(keyVaultConnectionInfo))
            {
                secret = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultEncryptionKey).Result;
            }

            using (BlockchainHelper blockchainHelper = new BlockchainHelper())
            {
                wordlist = blockchainHelper.ReadMnemonic();
            }
        }
Ejemplo n.º 28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("OAuthConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>((options) =>
            {
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 0;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication()
            .AddOAuthValidation()
            .AddOpenIdConnectServer(options =>
            {
                options.UserinfoEndpointPath      = "/api/v1/me";
                options.TokenEndpointPath         = "/api/v1/token";
                options.AuthorizationEndpointPath = "/authorize/";
                options.UseSlidingExpiration      = false;
                options.AllowInsecureHttp         = true;
                options.AccessTokenLifetime       = TimeSpan.FromHours(1);
                options.RefreshTokenLifetime      =
                    TimeSpan.FromDays(365 * 1000);
                options.AuthorizationCodeLifetime = TimeSpan.FromSeconds(60);
                options.IdentityTokenLifetime     = options.AccessTokenLifetime;
                options.ProviderType = typeof(OAuthProvider);

                // Register the HSM signing key.
                var keyPath          = Configuration.GetSection("KeyVault")["KeyPath"];
                var keyVaultEndpoint = Configuration.GetSection("KeyVault")["KeyVaultEndpoint"];
                options.SigningCredentials.AddKey(KeyVaultHelper.GetSigningKey(keyVaultEndpoint, keyPath));
            });

            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddScoped <OAuthProvider>();
            services.AddTransient <ValidationService>();
            services.AddTransient <TokenService>();
            services.AddSingleton <IAuthorizationPolicyProvider, AuthorizationPolicyProvider>();
            services.AddSingleton <IAuthorizationHandler, HasScopeHandler>();
            services.AddMvc();
            services.AddApplicationInsightsTelemetry();
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Process Record
        /// </summary>
        protected override void ProcessRecord()
        {
            bool Successful = KeyVaultHelper.SetItemsThrow(Id, VaultName, Location, VaultURI, SoftDeleteEnabled, Tags, Exact);

            if (Passthru)
            {
                Data.KeyVault[] results = KeyVaultHelper.GetItems(null, VaultName, true);

                // Unroll the object
                foreach (Data.KeyVault result in results)
                {
                    WriteObject(result);
                }
            }
        }
Ejemplo n.º 30
0
        private static void Init()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile("secrets/appsettings.secrets.json", optional: true)
                          .AddEnvironmentVariables();

            IConfigurationRoot Configuration = builder.Build();

            // Retrieve configuration from sections
            ApplicationSettings.ConnectionString        = Configuration.GetSection("ApplicationSettings:ConnectionString")?.Value;
            ApplicationSettings.DatabaseId              = Configuration.GetSection("ApplicationSettings:DatabaseId")?.Value;
            ApplicationSettings.ReportCollection        = Configuration.GetSection("ApplicationSettings:ReportCollection")?.Value;
            ApplicationSettings.RabbitMQUsername        = Configuration.GetSection("ApplicationSettings:RabbitMQUsername")?.Value;
            ApplicationSettings.RabbitMQPassword        = Configuration.GetSection("ApplicationSettings:RabbitMQPassword")?.Value;
            ApplicationSettings.RabbitMQHostname        = Configuration.GetSection("ApplicationSettings:RabbitMQHostname")?.Value;
            ApplicationSettings.RabbitMQPort            = Convert.ToInt16(Configuration.GetSection("ApplicationSettings:RabbitMQPort")?.Value);
            ApplicationSettings.DispatchQueueName       = Configuration.GetSection("ApplicationSettings:DispatchQueueName")?.Value;
            ApplicationSettings.KeyVaultCertificateName = Configuration.GetSection("ApplicationSettings:KeyVaultCertificateName")?.Value;
            ApplicationSettings.KeyVaultClientId        = Configuration.GetSection("ApplicationSettings:KeyVaultClientId")?.Value;
            ApplicationSettings.KeyVaultClientSecret    = Configuration.GetSection("ApplicationSettings:KeyVaultClientSecret")?.Value;
            ApplicationSettings.KeyVaultIdentifier      = Configuration.GetSection("ApplicationSettings:KeyVaultIdentifier")?.Value;
            ApplicationSettings.KeyVaultEncryptionKey   = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value;
            ApplicationSettings.SendGridAPIKey          = Configuration.GetSection("ApplicationSettings:SendGridAPIKey")?.Value;

            mongoDBConnectionInfo = new MongoDBConnectionInfo()
            {
                ConnectionString = ApplicationSettings.ConnectionString,
                DatabaseId       = ApplicationSettings.DatabaseId,
                UserCollection   = ApplicationSettings.ReportCollection
            };

            keyVaultConnectionInfo = new KeyVaultConnectionInfo()
            {
                CertificateName    = ApplicationSettings.KeyVaultCertificateName,
                ClientId           = ApplicationSettings.KeyVaultClientId,
                ClientSecret       = ApplicationSettings.KeyVaultClientSecret,
                KeyVaultIdentifier = ApplicationSettings.KeyVaultIdentifier
            };

            using (KeyVaultHelper keyVaultHelper = new KeyVaultHelper(keyVaultConnectionInfo))
            {
                secret = keyVaultHelper.GetVaultKeyAsync(ApplicationSettings.KeyVaultEncryptionKey).Result;
            }

            pdfTools  = new PdfTools();
            converter = new SynchronizedConverter(pdfTools);
        }