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;
        }
        /// <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;
        }
        /// <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 #5
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();
            }
        }