public void CustomActiveDirectoryProviderTest_AppClientId_DeviceFlowCallback()
        {
            SqlAuthenticationProvider authProvider = new ActiveDirectoryAuthenticationProvider(CustomDeviceFlowCallback, Guid.NewGuid().ToString());

            SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, authProvider);
            Assert.Equal(authProvider, SqlAuthenticationProvider.GetProvider(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow));
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry();

            /*
             * services.Configure<CookiePolicyOptions>(options =>
             * {
             *  // This lambda determines whether user consent for non-essential cookies is needed for a given request.
             *  options.CheckConsentNeeded = context => true;
             *  options.MinimumSameSitePolicy = SameSiteMode.None;
             * });
             */

            services.AddMvc().AddViewLocalization();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            if (Environment.EnvironmentName == "Development")
            {
                SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryMSI, new AzureIdentitySqlAuthenticationProvider());
                SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryManagedIdentity, new AzureIdentitySqlAuthenticationProvider());
            }

            services.AddDbContextPool <AlpinehutsDbContext>(options =>
            {
                options.UseSqlServer(Configuration["DatabaseConnectionString"]);
            });

            IMvcBuilder builder = services.AddRazorPages();

            if (Environment.EnvironmentName == "Development")
            {
                builder.AddRazorRuntimeCompilation();
            }
        }
        public void CustomActiveDirectoryProviderTest()
        {
            SqlAuthenticationProvider authProvider = new ActiveDirectoryAuthenticationProvider(CustomDeviceFlowCallback);

            SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, authProvider);
            Assert.Equal(authProvider, SqlAuthenticationProvider.GetProvider(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow));
        }
Esempio n. 4
0
        static void Main()
        {
            Console.WriteLine("Starting up Fight Quote App...");

            var builder = new SqlConnectionStringBuilder();

            builder.ConnectionString = Utility.GetConnectionStringByName("fightdata");

            Console.Write("Enter username: ");
            string username = Console.ReadLine();

            builder.UserID = username;

            builder.Authentication = SqlAuthenticationMethod.ActiveDirectoryInteractive;

            var provider = new ActiveDirectoryAuthProvider();
            SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider);

            Utility.GetConnectionStringInfo(builder);

            Utility.PrintBanner();

            Console.WriteLine(Utility.GetFightFact(builder.ConnectionString));

            Utility.PrintEnding();
        }
Esempio n. 5
0
        public static IServiceCollection AddDatabaseConfiguration(this IServiceCollection services,
                                                                  IConfiguration configuration)
        {
            if (configuration.GetValue <bool>("SQL_SERVER_USE_AZURE_AD_AUTHENTICATION"))
            {
                SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryIntegrated, new AzureSqlAuthenticationProvider());
            }

            var connectionString = configuration.GetConnectionString(nameof(SurveyContext));

            services.AddDbContext <SurveyContext>
                (options =>
            {
                options.UseSqlServer(connectionString,
                                     sqlServerOptions =>
                                     sqlServerOptions.EnableRetryOnFailure(15, TimeSpan.FromSeconds(30),
                                                                           null));
            }
                );

            services.AddScoped <ISurveyContext>(provider => provider.GetService <SurveyContext>());

            services.AddScoped <IDatabaseConnection>(_ => new DapperSqlServerConnection(connectionString));

            return(services);
        }
Esempio n. 6
0
 public static void Main()
 {
     SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, new CustomDeviceCodeFlowAzureAuthenticationProvider());
     using (SqlConnection sqlConnection = new SqlConnection("Server=<myserver>.database.windows.net;Authentication=Active Directory Device Code Flow;Database=<db>;"))
     {
         sqlConnection.Open();
         Console.WriteLine("Connected successfully!");
     }
 }
Esempio n. 7
0
        public string GetAuthToken(Uri connectedUri)
        {
            var uri        = new Uri(connectedUri, "/");
            var authParams = _authParams[uri.ToString()];
            var authProv   = SqlAuthenticationProvider.GetProvider(authParams.AuthenticationMethod);
            var token      = Task.Run(() => authProv.AcquireTokenAsync(authParams)).ConfigureAwait(false).GetAwaiter().GetResult();

            return(token.AccessToken);
        }
Esempio n. 8
0
        public static AlpinehutsDbContext GetDbContext()
        {
            SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryMSI, new AzureIdentitySqlAuthenticationProvider());
            SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryManagedIdentity, new AzureIdentitySqlAuthenticationProvider());

            DbContextOptionsBuilder <AlpinehutsDbContext> optionsBuilder = new DbContextOptionsBuilder <AlpinehutsDbContext>();

            // Using managed AAD identity to connect to the database
            var dbConnection = new SqlConnection(Environment.GetEnvironmentVariable("DatabaseConnectionString"));

            optionsBuilder.UseSqlServer(dbConnection, options => options.EnableRetryOnFailure());
            var alpinehutsDbContext = new AlpinehutsDbContext(optionsBuilder.Options);

            return(alpinehutsDbContext);
        }
Esempio n. 9
0
        public static void Main()
        {
            // Supported for all authentication modes supported by ActiveDirectoryAuthenticationProvider
            ActiveDirectoryAuthenticationProvider provider = new ActiveDirectoryAuthenticationProvider("<application_client_id>");

            if (provider.IsSupported(SqlAuthenticationMethod.ActiveDirectoryInteractive))
            {
                SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider);
            }

            using (SqlConnection sqlConnection = new SqlConnection("Server=<myserver>.database.windows.net;Authentication=Active Directory Interactive;Database=<db>;"))
            {
                sqlConnection.Open();
                Console.WriteLine("Connected successfully!");
            }
        }
        public async Task ConnectToSqlDbWithSqlAppAuthProvider()
        {
            // register SqlAzureAppAuthProvider and create the connection string
            SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, new SqlAppAuthenticationProvider());
            string connectionString = $"server={Environment.GetEnvironmentVariable(Constants.TestSqlDbEndpoint)};Authentication=Active Directory Interactive;UID=";

            // verify the connection can be successfully opened
            var sqlConnection = new SqlConnection(connectionString);
            await sqlConnection.OpenAsync();

            Assert.Equal(ConnectionState.Open, sqlConnection.State);

            // verify connection can be successfully closed
            sqlConnection.Close();
            Assert.Equal(ConnectionState.Closed, sqlConnection.State);
        }
        private async Task Run(Parameter parameter)
        {
            var provider = new LocalhostInteractiveSqlAuthenticationProvider(parameter.AzureClientId);

            SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider);

            using var connection = new SqlConnection(parameter.ConnectionString);
            await connection.OpenAsync().ConfigureAwait(false);

            using var command = new SqlCommand("select top (30) UserName from AspNetUsers order by UserName desc;", connection);
            var reader = await command.ExecuteReaderAsync().ConfigureAwait(false);

            while (await reader.ReadAsync().ConfigureAwait(false))
            {
                Console.WriteLine(reader["UserName"]);
            }
        }
Esempio n. 12
0
 public static void TestCustomProviderAuthentication()
 {
     SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryPassword, new CustomSqlAuthenticationProvider(DataTestUtility.ApplicationClientId));
     // Connect to Azure DB with password and retrieve user name using custom authentication provider
     using (SqlConnection conn = new SqlConnection(DataTestUtility.AADPasswordConnectionString))
     {
         conn.Open();
         using (SqlCommand sqlCommand = new SqlCommand
                                        (
                    cmdText: $"SELECT SUSER_SNAME();",
                    connection: conn,
                    transaction: null
                                        ))
         {
             string customerId = (string)sqlCommand.ExecuteScalar();
             string expected   = DataTestUtility.RetrieveValueFromConnStr(DataTestUtility.AADPasswordConnectionString, new string[] { "User ID", "UID" });
             Assert.Equal(expected, customerId);
         }
     }
     // Reset to driver internal provider.
     SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryPassword, new ActiveDirectoryAuthenticationProvider(DataTestUtility.ApplicationClientId));
 }
Esempio n. 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks();
            services.AddOptions();

            var serviceClientSettingsConfig = Configuration.GetSection("RabbitMq");

            services.Configure <RabbitMqConfiguration>(serviceClientSettingsConfig);

            serviceClientSettingsConfig = Configuration.GetSection("AzureServiceBus");
            services.Configure <AzureServiceBusConfiguration>(serviceClientSettingsConfig);

            bool.TryParse(Configuration["BaseServiceSettings:UseInMemoryDatabase"], out var useInMemory);
            bool.TryParse(Configuration["UseAadAuthentication"], out var useAadAuthentication);

            if (!useInMemory)
            {
                if (useAadAuthentication)
                {
                    services.AddDbContext <CustomerContext>(options =>
                    {
                        SqlAuthenticationProvider.SetProvider(
                            SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow,
                            new CustomAzureSqlAuthProvider(Configuration["TenantId"]));
                        var sqlConnection = new SqlConnection(Configuration.GetConnectionString("CustomerDatabase"));
                        options.UseSqlServer(sqlConnection);
                    });
                }
                else
                {
                    services.AddDbContext <CustomerContext>(options =>
                    {
                        options.UseSqlServer(Configuration.GetConnectionString("CustomerDatabase"));
                    });
                }
            }
            else
            {
                services.AddDbContext <CustomerContext>(options => options.UseInMemoryDatabase(Guid.NewGuid().ToString()));
            }

            services.AddAutoMapper(typeof(Startup));

            services.AddMvc().AddFluentValidation();

            services.AddEndpointsApiExplorer();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "Customer Api",
                    Description = "A simple API to create or update customers",
                    Contact     = new OpenApiContact
                    {
                        Name  = "Wolfgang Ofner",
                        Email = "*****@*****.**",
                        Url   = new Uri("https://www.programmingwithwolfgang.com/")
                    }
                });
            });

            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var actionExecutingContext =
                        actionContext as ActionExecutingContext;

                    if (actionContext.ModelState.ErrorCount > 0 &&
                        actionExecutingContext?.ActionArguments.Count == actionContext.ActionDescriptor.Parameters.Count)
                    {
                        return(new UnprocessableEntityObjectResult(actionContext.ModelState));
                    }

                    return(new BadRequestObjectResult(actionContext.ModelState));
                };
            });

            services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddTransient(typeof(IRepository <>), typeof(Repository <>));
            services.AddTransient <ICustomerRepository, CustomerRepository>();

            services.AddTransient <IValidator <CreateCustomerModel>, CreateCustomerModelValidator>();
            services.AddTransient <IValidator <UpdateCustomerModel>, UpdateCustomerModelValidator>();

            bool.TryParse(Configuration["BaseServiceSettings:UserabbitMq"], out var useRabbitMq);

            if (useRabbitMq)
            {
                services.AddSingleton <ICustomerUpdateSender, CustomerUpdateSender>();
            }
            else
            {
                services.AddSingleton <ICustomerUpdateSender, CustomerUpdateSenderServiceBus>();
            }

            services.AddTransient <IRequestHandler <CreateCustomerCommand, Customer>, CreateCustomerCommandHandler>();
            services.AddTransient <IRequestHandler <UpdateCustomerCommand, Customer>, UpdateCustomerCommandHandler>();
            services.AddTransient <IRequestHandler <GetCustomerByIdQuery, Customer>, GetCustomerByIdQueryHandler>();
            services.AddTransient <IRequestHandler <GetCustomersQuery, List <Customer> >, GetCustomersQueryHandler>();

            services.AddSingleton <MetricCollector>();
        }
 public TodosController()
 {
     SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, new SqlAppAuthenticationProvider());
     db = new MyDatabaseContext();
 }