public MyWebDbContext(DbContextOptions <MyWebDbContext> options)
            : base(options)
        {
            var conn = (Microsoft.Data.SqlClient.SqlConnection)Database.GetDbConnection();
            var prov = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();

            conn.AccessToken = prov.GetAccessTokenAsync("https://database.windows.net/").Result;
        }
        public MyDatabaseContext(DbContextOptions <MyDatabaseContext> options)
            : base(options)
        {
            var    conn        = (System.Data.SqlClient.SqlConnection)Database.GetDbConnection();
            string accesstoken = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net/").Result;

            //if the user belogns to more subscriptions/tenants, add tenantID
            //string accesstoken = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net/", "<tenantid>").Result;
            conn.AccessToken = accesstoken;
        }
Exemple #3
0
        /// <summary>
        /// Gets the stored key vault configuration.
        /// </summary>
        /// <param name="configuration">IConfiguration.</param>
        /// <param name="deliveryChannelSecretUrl">Azure Key Vault URL where the delivery channel's configuration is stored.</param>
        /// <returns>Delivery channel secret.</returns>
        public static async Task <string> GetDeliveryChannelSecretAsync(IConfiguration configuration, string deliveryChannelSecretUrl)
        {
            string?azureConnectionString     = configuration.GetValue <string>("AzureServicesAuthConnectionString");
            var    azureServiceTokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider(azureConnectionString);

            using var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            Microsoft.Azure.KeyVault.Models.SecretBundle accountKey = await keyVaultClient.GetSecretAsync(deliveryChannelSecretUrl).ConfigureAwait(false);

            return(accountKey.Value);
        }
        /// <summary>
        /// This should be called before any call to <see cref="IRestClient"/>,
        /// it sets up the auth token and default headers per the AMS V2 API specification.
        /// </summary>
        private void ConfigureRestClient()
        {
            if (!isConfigured)
            {
                Exception exceptionInLock = null;
                lock (configLock)
                {
                    if (!isConfigured)
                    {
                        try
                        {
                            string amsRestApiEndpoint = GetAmsRestApiEndpoint();
                            _restClient = new RestClient(amsRestApiEndpoint);

                            // Acquire a token for AMS.
                            // Ref: https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#asal
                            var    azureServiceTokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
                            string amsAccessToken            = azureServiceTokenProvider.GetAccessTokenAsync(AmsRestApiResource).Result;

                            _restClient.Authenticator = new JwtAuthenticator(amsAccessToken);

                            _restClient.UseNewtonsoftJson(
                                new Newtonsoft.Json.JsonSerializerSettings()
                            {
                                ContractResolver = new DefaultContractResolver(),
                            });

                            _restClient.AddDefaultHeader("Content-Type", $"{ContentType.Json};odata=verbose");
                            _restClient.AddDefaultHeader("Accept", $"{ContentType.Json};odata=verbose");
                            _restClient.AddDefaultHeader("DataServiceVersion", "3.0");
                            _restClient.AddDefaultHeader("MaxDataServiceVersion", "3.0");
                            _restClient.AddDefaultHeader("x-ms-version", "2.19");
                        }
                        catch (Exception e)
                        {
                            exceptionInLock = e;
                            _log.LogError(e, $"Failed in {nameof(ConfigureRestClient)}.\nException.Message:\n{e.Message}\nInnerException.Message:\n{e.InnerException?.Message}");
                        }
                        finally
                        {
                            isConfigured = true;
                        }
                    }
                }

                if (exceptionInLock != null)
                {
                    throw exceptionInLock;
                }
            }

            return;
        }
Exemple #5
0
 public AzureServiceTokenProviderCredentials(string tenantIdentity, string resourceIdentity)
 {
     if (string.IsNullOrWhiteSpace(_resourceIdentity))
     {
         _resourceIdentity = "https://storage.azure.com/";
     }
     else
     {
         _resourceIdentity = resourceIdentity;
     }
     _tenantIdentity = tenantIdentity;
     _tokenProvider  = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
 }
        /// <summary>
        /// Gets the AMS V2 API endpoint.
        /// </summary>
        /// <returns>The AMS V2 API endpoint.</returns>
        private string GetAmsRestApiEndpoint()
        {
            string amsRestApiEndpoint;

            try
            {
                // Create a rest client for access the Azure Resource Management API Endpoint:
                var restManagementClient = new RestClient(_armManagementUrl);

                // Acquire a token for arm.
                // Ref: https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#asal
                var    azureServiceTokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
                string armAccessToken            = azureServiceTokenProvider.GetAccessTokenAsync(_armManagementUrl).Result;

                // Add the bearer authentication token to all requests:
                restManagementClient.Authenticator = new JwtAuthenticator(armAccessToken);

                // Enforce a known serializer:
                restManagementClient.UseNewtonsoftJson(
                    new Newtonsoft.Json.JsonSerializerSettings()
                {
                    ContractResolver = new DefaultContractResolver(),
                });

                // Add default headers
                restManagementClient.AddDefaultHeader("Accept", $"{ContentType.Json};odata=verbose");
                restManagementClient.AddDefaultHeader("Content-Type", ContentType.Json);

                // GET ams account details:
                var request      = new RestRequest(_armAmsAccoutGetPath, Method.GET);
                var restResponse = restManagementClient.Execute <JObject>(request);
                if (!restResponse.IsSuccessful)
                {
                    string expMsg = "Failed to get ams account details.";
                    throw new Exception(expMsg);
                }

                // Parse endpoint information from arm response.
                amsRestApiEndpoint = (string)restResponse.Data.SelectToken("properties.apiEndpoints[0].endpoint");
            }
            catch (Exception e)
            {
                // Just log, let the caller catch the original exception:
                _log.LogError(e, $"Failed in {nameof(GetAmsRestApiEndpoint)}.\nException.Message:\n{e.Message}\nInnerException.Message:\n{e.InnerException?.Message}");
                throw;
            }

            return(amsRestApiEndpoint);
        }
 public string GetAzureRestApiToken(string ServiceURI, bool UseMSI, string ApplicationId, string AuthenticationKey)
 {
     if (UseMSI == true)
     {
         Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider tokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
         //https://management.azure.com/
         return(tokenProvider.GetAccessTokenAsync(ServiceURI).Result);
     }
     else
     {
         AuthenticationContext context = new AuthenticationContext("https://login.windows.net/" + _authOptions.Value.TenantId);
         ClientCredential      cc      = new ClientCredential(ApplicationId, AuthenticationKey);
         AuthenticationResult  result  = context.AcquireTokenAsync(ServiceURI, cc).Result;
         return(result.AccessToken);
     }
 }
Exemple #8
0
        private string ValidateConnectionStringWithoutPassword(string connection, string clientId, string tenantId, string appSecret, string resourceName)
        {
            if (string.IsNullOrEmpty(connection))
            {
                return("Connection string is empty");
            }

            if (string.IsNullOrEmpty(clientId) || !Guid.TryParse(clientId, out _))
            {
                return("Invalid client/app id.");
            }

            if (string.IsNullOrEmpty(tenantId) || !Guid.TryParse(tenantId, out _))
            {
                return("Invalid tenant id.");
            }

            if (string.IsNullOrEmpty(appSecret))
            {
                return("App secret is empty");
            }

            if (string.IsNullOrEmpty(resourceName))
            {
                return("Resource name is empty");
            }

            SqlConnection con = new SqlConnection(connection);

            try
            {
                var tokenProv = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider($"RunAs=App;AppId={clientId};TenantId={tenantId};AppKey={appSecret}");
                con.AccessToken = tokenProv.GetAccessTokenAsync(resourceName).Result;
                con.Open();
                return("Connection success.");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }
        public MentorDbContext(DbContextOptions <MentorDbContext> options, IHttpContextAccessor httpContextAccessor, ILogger <MentorDbContext> logger)
            : base(options)
        {
            this.httpContextAccessor = httpContextAccessor;
            this.logger = logger;

            var conn = (Microsoft.Data.SqlClient.SqlConnection)Database.GetDbConnection();

            if (conn.ConnectionString.Contains("database.usgovcloudapi.net", StringComparison.OrdinalIgnoreCase))
            {
                var provider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
                conn.AccessToken = provider.GetAccessTokenAsync("https://database.usgovcloudapi.net/").ConfigureAwait(true).GetAwaiter().GetResult();
            }
            if (conn.ConnectionString.Contains("database.windows.net", StringComparison.OrdinalIgnoreCase))
            {
                var provider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
                conn.AccessToken = provider.GetAccessTokenAsync("https://database.windows.net/").ConfigureAwait(true).GetAwaiter().GetResult();
            }
        }
Exemple #10
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            // read config from KV if env is prod else read from appsetting.json
            if (context.HostingEnvironment.IsProduction())
            {
                var builtConfig = config.Build();
                var kvacct      = builtConfig["app:kvacct"];

                Trace.WriteLine($"TRACE:kevault url= https://{kvacct}.vault.azure.net/");

                var azureServiceTokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
                var keyVaultClient            = new KeyVaultClient(
                    new KeyVaultClient.AuthenticationCallback(
                        azureServiceTokenProvider.KeyVaultTokenCallback));

                config.AddAzureKeyVault(
                    $"https://{kvacct}.vault.azure.net/",
                    keyVaultClient,
                    new DefaultKeyVaultSecretManager());
            }
        })
        .UseStartup <Startup>();
                public AzureServiceTokenProviderCredentials(string tenantIdentity, string resourceIdentity, string clientIdentity)
                {
                    if (string.IsNullOrWhiteSpace(_resourceIdentity))
                    {
                        _resourceIdentity = "https://database.windows.net/";
                    }
                    else
                    {
                        _resourceIdentity = resourceIdentity;
                    }
                    if (!string.IsNullOrWhiteSpace(tenantIdentity))
                    {
                        _tenantIdentity = tenantIdentity;
                    }

                    if (string.IsNullOrWhiteSpace(clientIdentity))
                    {
                        _tokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
                    }
                    else
                    {
                        _tokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider($"RunAs=App;AppId={clientIdentity}");
                    }
                }