Beispiel #1
0
        /// <summary>
        /// Configure Services
        /// </summary>
        /// <param name="services"></param>
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DemoDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))
            .AddDbContext <DemoDbContext>(o => o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddMvc(opt =>
            {
                opt.Filters.Add(typeof(ValidatorActionFilter));
            });

            //  For Cross-orgin
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
                //.WithOrigins("http://example.com");
            }));

            //Swagger Configuration and Add Swagger generation Document
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Demo API V1.0", Version = "v1"
                });

                // Set the comments path for the Swagger JSON and UI.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "Demo.API.xml");
                c.IncludeXmlComments(xmlPath);
            });

            services.AddMvc();

            // Config IOC
            IOCConfig.Register(services);
        }
        /// <summary>
        /// Configure Services
        /// </summary>
        /// <param name="services"></param>
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <BearerTokensOptions>(options => Configuration.GetSection("BearerTokens").Bind(options));
            services.Configure <ApiSettings>(options => Configuration.GetSection("ApiSettings").Bind(options));


            services.AddDbContext <DemoDbContext>(options =>
            {
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection"),
                    serverDbContextOptionsBuilder =>
                {
                    var minutes = (int)TimeSpan.FromMinutes(3).TotalSeconds;
                    serverDbContextOptionsBuilder.CommandTimeout(minutes);
                    serverDbContextOptionsBuilder.EnableRetryOnFailure();
                });
            });

            //services.AddDbContext<DemoDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))
            //        .AddDbContext<DemoDbContext>(o => o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //services.AddIdentity<User, Role>()
            //        .AddEntityFrameworkStores<DemoDbContext>()
            //        .AddDefaultTokenProviders();

            services.AddMvc(opt =>
            {
                opt.Filters.Add(typeof(ValidatorActionFilter));
                opt.Filters.Add(typeof(CustomExceptionFilter));
            });

            //Swagger Configuration and Add Swagger generation Document
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Demo API V1.0", Version = "v1"
                });
                // Add jwt token in heaer.
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme {
                    In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() }
                });

                // Set the comments path for the Swagger JSON and UI.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "Demo.API.xml");
                c.IncludeXmlComments(xmlPath);
            });

            services.AddMvcCore(options =>
            {
                //options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            }).AddAuthorization(options =>
            {
                options.AddPolicy(CustomRoles.Admin.ConvertToString(), policy => policy.RequireRole(CustomRoles.Admin.ConvertToString()));
                options.AddPolicy(CustomRoles.User.ConvertToString(), policy => policy.RequireRole(CustomRoles.User.ConvertToString()));
                options.AddPolicy(CustomRoles.Editor.ConvertToString(), policy => policy.RequireRole(CustomRoles.Editor.ConvertToString()));
            });
            //.AddJsonFormatters(options => options.ContractResolver = new CamelCasePropertyNamesContractResolver()); ;

            // Needed for jwt auth.
            services
            .AddAuthentication(options =>
            {
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer              = Configuration["BearerTokens:Issuer"],   // site that makes the token
                    ValidateIssuer           = false,                                  // TODO: change this to avoid forwarding attacks
                    ValidAudience            = Configuration["BearerTokens:Audience"], // site that consumes the token
                    ValidateAudience         = false,                                  // TODO: change this to avoid forwarding attacks
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["BearerTokens:Key"])),
                    ValidateIssuerSigningKey = true,                                   // verify signature to avoid tampering
                    ValidateLifetime         = true,                                   // validate the expiration
                    ClockSkew = TimeSpan.Zero                                          // tolerance for the expiration date
                };
                cfg.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        var logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("Authentication failed.", context.Exception);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        var tokenValidatorService = context.HttpContext.RequestServices.GetRequiredService <ITokenValidatorService>();
                        return(tokenValidatorService.ValidateAsync(context));
                    },
                    OnMessageReceived = context =>
                    {
                        return(Task.CompletedTask);
                    },
                    OnChallenge = context =>
                    {
                        var logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("OnChallenge error", context.Error, context.ErrorDescription);
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddDataProtection()
            .UseCryptographicAlgorithms(
                new AuthenticatedEncryptorConfiguration()
            {
                EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
                ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
            })
            .SetDefaultKeyLifetime(TimeSpan.FromDays(7));

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                  .WithOrigins("http://localhost:4200") //Note:  The URL must be specified without a trailing slash (/).
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            //services.AddAntiforgery(x =>
            //{
            //    x.HeaderName = "X-XSRF-TOKEN";
            //    x.SuppressXFrameOptionsHeader = false;
            //});


            // Config IOC
            IOCConfig.Register(services);
        }