Exemple #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //inject im-mem cache
            //services.AddMemoryCache();

            //Inject db context
            services.AddDbContext <CLToolContext>(options =>
                                                  options.UseSqlServer(Configuration.GetConnectionString("Default")));
            //Inject config
            services.AddSingleton <IConfiguration>(Configuration);
            //Inject indus adapter
            services.AddSingleton <ICustomerAdapter>(IndusFactory.GetIndusInstance(Configuration,
                                                                                   File.ReadAllText($"{ExeDir}\\{Configuration.GetSection("Indus").GetValue<string>("QueryFileName")}")));

            //services.AddSingleton<ICustomerAdapter>(IndusFactory.GetMockInstance());

            //auth service
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                       options =>
            {
                options.Cookie.Expiration = TimeSpan.FromMinutes(120);
                // access inner page w/o cred will get redirected to this
                options.LoginPath         = new PathString("/Account/Login");
                options.AccessDeniedPath  = new PathString("/Account/Forbidden");
                options.LogoutPath        = new PathString("/Account/Logout");
                options.SlidingExpiration = true;     //extend cookie exp as user still on the site
                //just for fun, cant find a clean way to use this :/
                //bc url query doesnt play well with form submit in Account/DoLogin
                options.ReturnUrlParameter = "returnUrl";
            });
            //Compression
            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
                //Everything else is too small to compress
                options.MimeTypes = new[] { "text/css", "application/javascript" };
            });

            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                options.Level = System.IO.Compression.CompressionLevel.Fastest;
            });


            //enforce SSL
            //services.Configure<MvcOptions>(options =>
            //{
            //    options.Filters.Add(new RequireHttpsAttribute());
            //});
            //https://github.com/aspnet/Mvc/issues/4842

            services.AddSession(options =>
            {
                options.Cookie.Name = "s";
            });
            services.AddMvc().AddJsonOptions(options =>
            {
                //solve auto camel case prop names
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //ignore loop ref of object contains each other
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //inject im-mem cache
            //services.AddMemoryCache();
            //Jwt
            services.AddSingleton <IJwtFactory, JwtFactory>();

            //Inject db context
            services.AddDbContext <DocumentArchiverContext>(options =>
                                                            options.UseSqlServer(Configuration.GetConnectionString("Default")));
            //Inject config
            services.AddSingleton <IConfiguration>(Configuration);

            services.AddSingleton <IIndusAdapter>(IndusFactory.GetIndusInstance(Configuration,
                                                                                File.ReadAllText($"{Program.ExeDir}\\{Configuration.GetSection("Indus").GetValue<string>("QueryFileName")}")));

            //cookie auth service
            //services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            //        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
            //    options =>
            //    {
            //        options.Cookie.Expiration = TimeSpan.FromMinutes(120);
            //        // access inner page w/o cred will get redirected to this
            //        options.LoginPath = new PathString("/Account/Login");
            //        options.AccessDeniedPath = new PathString("/Account/Forbidden");
            //        options.LogoutPath = new PathString("/Account/Logout");
            //        options.SlidingExpiration = true; //extend cookie exp as user still on the site
            //        //just for fun, cant find a clean way to use this :/
            //        //bc url query doesnt play well with form submit in Account/DoLogin
            //        options.ReturnUrlParameter = "returnUrl";
            //    });

            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = _signingKey,

                RequireExpirationTime = false,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;
            });

            //policy
            services.AddAuthorization(options =>
            {
                options.AddPolicy(AbilityList.Create, policy => policy.RequireClaim(AppConst.Ability, AbilityList.Create));
                options.AddPolicy(AbilityList.Delete, policy => policy.RequireClaim(AppConst.Ability, AbilityList.Delete));
                options.AddPolicy(AbilityList.Update, policy => policy.RequireClaim(AppConst.Ability, AbilityList.Update));
                options.AddPolicy(AbilityList.Download, policy => policy.RequireClaim(AppConst.Ability, AbilityList.Download));
                options.AddPolicy(AbilityList.ManageUser, policy => policy.RequireClaim(AppConst.Ability, AbilityList.ManageUser));
            });

            //Compression
            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
                //Everything else is too small to compress
                options.MimeTypes = new[] { "text/css", "application/javascript" };
            });

            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                options.Level = System.IO.Compression.CompressionLevel.Fastest;
            });


            //enforce SSL
            //services.Configure<MvcOptions>(options =>
            //{
            //    options.Filters.Add(new RequireHttpsAttribute());
            //});
            //https://github.com/aspnet/Mvc/issues/4842

            services.AddSession(options =>
            {
                options.Cookie.Name = "s";
            });
            services.AddMvc().AddJsonOptions(options =>
            {
                //solve auto camel case prop names
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //ignore loop ref of object contains each other
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });
        }