Example #1
0
    public void ConfigureServices(IServiceCollection services)
    {
        var databaseUri = Configuration["cleardb:0:credentials:uri"];

        if (!string.IsNullOrEmpty(databaseUri))
        {
            // add database context
            services.AddDbContext <PreventionAdvisorDbContext>(options => options.UseMySQL(getConnectionString(databaseUri)));
        }

        // Add CORS
        services.AddCors();

        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.CookieHttpOnly = true;
            options.CookieName     = ".PreventionAdvisor.Session";
        });

        // Add framework services.
        services.AddMvc();

        // Always use HTTPS
#if !DEBUG
        services.AddMvc(config => {
            config.Filters.Add(new RequireHttpsAttribute());
        });
#endif

        // Add Identity
        services.AddIdentity <IdentityUser, IdentityRole>(config =>
        {
            config.User.RequireUniqueEmail             = true;
            config.Password.RequiredLength             = 8;
            config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
            config.Cookies.ApplicationCookie.Events    = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = async ctx =>
                {
                    if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                    {
                        ctx.Response.StatusCode = 401;
                    }
                    else
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }

                    await Task.Yield();
                }
            };
        })
        .AddEntityFrameworkStores <PreventionAdvisorDbContext>()
        .AddDefaultTokenProviders();


        // Add automapper
        MapperConfig.CreateMappings();
    }