This class holds various configuration values used by the Tailspin.Surveys.Web project.
        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            var configOptions = new SurveyAppConfiguration.ConfigurationOptions();

            Configuration.Bind(configOptions);

            // Configure the HTTP request pipeline.
            // Add the following to the request pipeline only in development environment.
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <SurveyAppConfiguration.ConfigurationOptions>(options => Configuration.Bind(options));

            var configOptions = new SurveyAppConfiguration.ConfigurationOptions();

            Configuration.Bind(configOptions);

            // This will add the Redis implementation of IDistributedCache
            services.AddDistributedRedisCache(setup => {
                setup.Configuration = configOptions.Redis.Configuration;
            });

            // This will only add the LocalCache implementation of IDistributedCache if there is not an IDistributedCache already registered.
            services.AddMemoryCache();

            //services.AddAuthentication(sharedOptions =>
            //    sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);

            services.AddAuthorization(options =>
            {
                options.AddPolicy(PolicyNames.RequireSurveyCreator,
                                  policy =>
                {
                    policy.AddRequirements(new SurveyCreatorRequirement());
                    policy.RequireAuthenticatedUser();     // Adds DenyAnonymousAuthorizationRequirement
                    // By adding the CookieAuthenticationDefaults.AuthenticationScheme,
                    // if an authenticated user is not in the appropriate role, they will be redirected to the "forbidden" experience.
                    policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                });

                options.AddPolicy(PolicyNames.RequireSurveyAdmin,
                                  policy =>
                {
                    policy.AddRequirements(new SurveyAdminRequirement());
                    policy.RequireAuthenticatedUser();     // Adds DenyAnonymousAuthorizationRequirement
                    // By adding the CookieAuthenticationDefaults.AuthenticationScheme,
                    // if an authenticated user is not in the appropriate role, they will be redirected to the "forbidden" experience.
                    policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                });
            });

            // Add Entity Framework services to the services container.
            services.AddEntityFrameworkSqlServer()
            .AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetSection("Data")["SurveysConnectionString"]));

            // Add MVC services to the services container.
            services.AddMvc();

            // Register application services.

            // This will register IDistributedCache based token cache which ADAL will use for caching access tokens.
            services.AddScoped <ITokenCacheService, DistributedTokenCacheService>();

            services.AddScoped <ISurveysTokenService, SurveysTokenService>();
            services.AddSingleton <HttpClientService>();

            // Uncomment the following line to use client certificate credentials.
            //services.AddSingleton<ICredentialService, CertificateCredentialService>();

            // Comment out the following line if you are using client certificates.
            services.AddSingleton <ICredentialService, ClientCredentialService>();

            services.AddScoped <ISurveyService, SurveyService>();
            services.AddScoped <IQuestionService, QuestionService>();
            services.AddScoped <SignInManager, SignInManager>();
            services.AddScoped <TenantManager, TenantManager>();
            services.AddScoped <UserManager, UserManager>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        }
        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var configOptions = new SurveyAppConfiguration.ConfigurationOptions();

            Configuration.Bind(configOptions);

            // Configure the HTTP request pipeline.
            // Add the following to the request pipeline only in development environment.
            if (env.IsDevelopment())
            {
                //app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                app.UseExceptionHandler("/Home/Error");
            }

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // Add cookie-based authentication to the request pipeline.
            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                AccessDeniedPath      = "/Home/Forbidden",
                CookieSecure          = CookieSecurePolicy.Always,

                // The default setting for cookie expiration is 14 days. SlidingExpiration is set to true by default
                ExpireTimeSpan    = TimeSpan.FromHours(1),
                SlidingExpiration = true
            });

            // Add OpenIdConnect middleware so you can login using Azure AD.
            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions {
                ClientId                  = configOptions.AzureAd.ClientId,
                ClientSecret              = configOptions.AzureAd.ClientSecret, // for code flow
                Authority                 = Constants.AuthEndpointPrefix,
                ResponseType              = OpenIdConnectResponseType.CodeIdToken,
                PostLogoutRedirectUri     = configOptions.AzureAd.PostLogoutRedirectUri,
                SignInScheme              = CookieAuthenticationDefaults.AuthenticationScheme,
                TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer = false
                },
                Events = new SurveyAuthenticationEvents(configOptions.AzureAd, loggerFactory),
            });

            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.AddDebug();
                builder.SetMinimumLevel(LogLevel.Information);
            });

            services.Configure <SurveyAppConfiguration.ConfigurationOptions>(options => Configuration.Bind(options));
            var configOptions = new SurveyAppConfiguration.ConfigurationOptions();

            Configuration.Bind(configOptions);

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o =>
            {
                o.AccessDeniedPath    = "/Home/Forbidden";
                o.ExpireTimeSpan      = TimeSpan.FromHours(1);
                o.SlidingExpiration   = true;
                o.Cookie              = (o.Cookie ?? new CookieBuilder());
                o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            })
            .AddOpenIdConnect(o =>
            {
                o.ClientId                  = configOptions.AzureAd.ClientId;
                o.ClientSecret              = configOptions.AzureAd.ClientSecret;
                o.Authority                 = Constants.AuthEndpointPrefix;
                o.ResponseType              = OpenIdConnectResponseType.CodeIdToken;
                o.SignedOutRedirectUri      = configOptions.AzureAd.PostLogoutRedirectUri;
                o.SignInScheme              = CookieAuthenticationDefaults.AuthenticationScheme;
                o.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer = false
                };
                o.Events = new SurveyAuthenticationEvents(configOptions.AzureAd, loggerFactory);
            });

            // This will add the Redis implementation of IDistributedCache
            services.AddDistributedRedisCache(setup =>
            {
                setup.Configuration = configOptions.Redis.Configuration;
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(PolicyNames.RequireSurveyCreator,
                                  policy =>
                {
                    policy.AddRequirements(new SurveyCreatorRequirement());
                    policy.RequireAuthenticatedUser();     // Adds DenyAnonymousAuthorizationRequirement
                    // By adding the CookieAuthenticationDefaults.AuthenticationScheme,
                    // if an authenticated user is not in the appropriate role, they will be redirected to the "forbidden" experience.
                    policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                });

                options.AddPolicy(PolicyNames.RequireSurveyAdmin,
                                  policy =>
                {
                    policy.AddRequirements(new SurveyAdminRequirement());
                    policy.RequireAuthenticatedUser();     // Adds DenyAnonymousAuthorizationRequirement
                    // By adding the CookieAuthenticationDefaults.AuthenticationScheme,
                    // if an authenticated user is not in the appropriate role, they will be redirected to the "forbidden" experience.
                    policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                });
            });

            // Add Entity Framework services to the services container.
            services.AddEntityFrameworkSqlServer()
            .AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetSection("Data")["SurveysConnectionString"]));

            // Add MVC services to the services container.
            services.AddControllersWithViews();

            // Register application services.

            // This will register IDistributedCache based token cache which ADAL will use for caching access tokens.
            services.AddScoped <ITokenCacheService, DistributedTokenCacheService>();
            services.AddScoped <ISurveysTokenService, SurveysTokenService>();
            services.AddSingleton <HttpClientService>();

            // Uncomment the following line to use client certificate credentials.
            //services.AddSingleton<ICredentialService, CertificateCredentialService>();

            // Comment out the following line if you are using client certificates.
            services.AddSingleton <ICredentialService, ClientCredentialService>();

            services.AddScoped <ISurveyService, SurveyService>();
            services.AddScoped <IQuestionService, QuestionService>();
            services.AddScoped <SignInManager, SignInManager>();
            services.AddScoped <TenantManager, TenantManager>();
            services.AddScoped <UserManager, UserManager>();
            services.AddHttpContextAccessor();
        }
Example #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var configOptions = new SurveyAppConfiguration.ConfigurationOptions();

            _configuration.Bind(configOptions);

            var adOptions = configOptions.AzureAd;

            services.Configure <SurveyAppConfiguration.ConfigurationOptions>(_configuration);

#if DNX451
            // This will add the Redis implementation of IDistributedCache
            services.AddRedisCache();
            services.Configure <Microsoft.Extensions.Caching.Redis.RedisCacheOptions>(options =>
            {
                options.Configuration = configOptions.Redis.Configuration;
            });
#endif

            // This will only add the LocalCache implementation of IDistributedCache if there is not an IDistributedCache already registered.
            services.AddCaching();

            services.AddAuthorization(options =>
            {
                options.AddPolicy(PolicyNames.RequireSurveyCreator,
                                  policy =>
                {
                    policy.AddRequirements(new SurveyCreatorRequirement());
                    policy.RequireAuthenticatedUser();     // Adds DenyAnonymousAuthorizationRequirement
                    // By adding the CookieAuthenticationDefaults.AuthenticationScheme,
                    // if an authenticated user is not in the appropriate role, they will be redirected to the "forbidden" experience.
                    policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                });

                options.AddPolicy(PolicyNames.RequireSurveyAdmin,
                                  policy =>
                {
                    policy.AddRequirements(new SurveyAdminRequirement());
                    policy.RequireAuthenticatedUser();     // Adds DenyAnonymousAuthorizationRequirement
                    // By adding the CookieAuthenticationDefaults.AuthenticationScheme,
                    // if an authenticated user is not in the appropriate role, they will be redirected to the "forbidden" experience.
                    policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                });
            });

            // Add Entity Framework services to the services container.
            services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(configOptions.Data.SurveysConnectionString));

            // Add MVC services to the services container.
            services.AddMvc();

            // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
            // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
            // services.AddWebApiConventions();

            // Register application services.

            // This will register IDistributedCache based token cache which ADAL will use for caching access tokens.
            services.AddScoped <ITokenCacheService, DistributedTokenCacheService>();

            services.AddScoped <ISurveysTokenService, SurveysTokenService>();
            services.AddSingleton <HttpClientService>();

            // Use this for client certificate support
            //services.AddSingleton<ICredentialService, CertificateCredentialService>();
            services.AddSingleton <ICredentialService, ClientCredentialService>();
            services.AddScoped <ISurveyService, SurveyService>();
            services.AddScoped <IQuestionService, QuestionService>();
            services.AddScoped <SignInManager, SignInManager>();
            services.AddScoped <TenantManager, TenantManager>();
            services.AddScoped <UserManager, UserManager>();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var configOptions = new SurveyAppConfiguration.ConfigurationOptions();
            _configuration.Bind(configOptions);

            var adOptions = configOptions.AzureAd;
            services.Configure<SurveyAppConfiguration.ConfigurationOptions>(_configuration);

#if DNX451
            // This will add the Redis implementation of IDistributedCache
            services.AddRedisCache();
            services.Configure<Microsoft.Extensions.Caching.Redis.RedisCacheOptions>(options =>
            {
                options.Configuration = configOptions.Redis.Configuration;
            });
#endif

            // This will only add the LocalCache implementation of IDistributedCache if there is not an IDistributedCache already registered.
            services.AddCaching();

            services.AddAuthorization(options =>
            {
                options.AddPolicy(PolicyNames.RequireSurveyCreator,
                    policy =>
                    {
                        policy.AddRequirements(new SurveyCreatorRequirement());
                        policy.RequireAuthenticatedUser(); // Adds DenyAnonymousAuthorizationRequirement 
                        // By adding the CookieAuthenticationDefaults.AuthenticationScheme,
                        // if an authenticated user is not in the appropriate role, they will be redirected to the "forbidden" experience.
                        policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                    });

                options.AddPolicy(PolicyNames.RequireSurveyAdmin,
                    policy =>
                    {
                        policy.AddRequirements(new SurveyAdminRequirement());
                        policy.RequireAuthenticatedUser(); // Adds DenyAnonymousAuthorizationRequirement 
                        // By adding the CookieAuthenticationDefaults.AuthenticationScheme,
                        // if an authenticated user is not in the appropriate role, they will be redirected to the "forbidden" experience.
                        policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                    });
            });

            // Add Entity Framework services to the services container.
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(configOptions.Data.SurveysConnectionString));

            // Add MVC services to the services container.
            services.AddMvc();

            // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
            // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
            // services.AddWebApiConventions();

            // Register application services.

            // This will register IDistributedCache based token cache which ADAL will use for caching access tokens.
            services.AddScoped<ITokenCacheService, DistributedTokenCacheService>();

            services.AddScoped<ISurveysTokenService, SurveysTokenService>();
            services.AddSingleton<HttpClientService>();

            // Use this for client certificate support
            //services.AddSingleton<ICredentialService, CertificateCredentialService>();
            services.AddSingleton<ICredentialService, ClientCredentialService>();
            services.AddScoped<ISurveyService, SurveyService>();
            services.AddScoped<IQuestionService, QuestionService>();
            services.AddScoped<SignInManager, SignInManager>();
            services.AddScoped<TenantManager, TenantManager>();
            services.AddScoped<UserManager, UserManager>();
        }
        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var configOptions = new SurveyAppConfiguration.ConfigurationOptions();
            Configuration.Bind(configOptions);

            // Configure the HTTP request pipeline.
            // Add the following to the request pipeline only in development environment.
            if (env.IsDevelopment())
            {
                //app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                app.UseExceptionHandler("/Home/Error");
            }

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // Add cookie-based authentication to the request pipeline.
            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                AccessDeniedPath = "/Home/Forbidden",
                CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always,

                // The default setting for cookie expiration is 14 days. SlidingExpiration is set to true by default
                ExpireTimeSpan = TimeSpan.FromHours(1),
                SlidingExpiration = true
            });

            // Add OpenIdConnect middleware so you can login using Azure AD.
            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions {
                ClientId = configOptions.AzureAd.ClientId,
                ClientSecret = configOptions.AzureAd.ClientSecret, // for code flow
                Authority = Constants.AuthEndpointPrefix,
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                PostLogoutRedirectUri = configOptions.AzureAd.PostLogoutRedirectUri,
                SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme,
                TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false },
                Events = new SurveyAuthenticationEvents(configOptions.AzureAd, loggerFactory),
            });

            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            });
        }