Exemple #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
            var connectionString   = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext <KVDbContext>(options =>
            {
                options.UseNpgsql(connectionString,
                                  optionsBuilder =>
                                  optionsBuilder.MigrationsAssembly(migrationsAssembly));
            });

            services.Configure <TokenConfig>(Configuration.GetSection("TokenConfig"));
            var token  = Configuration.GetSection("TokenConfig").Get <TokenConfig>();
            var secret = Encoding.ASCII.GetBytes(token.Secret);

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                                  builder =>
                {
                    builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                    ValidIssuer      = token.Issuer,
                    ValidAudience    = token.Audience,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                };
            });

            MappingConfiguration.Execute();

            services.AddScoped <IAuthenticationService, AuthenticationService>();
            services.AddTransientLazy <IUserService, UserService>();
            services.AddTransientLazy <ICustomerService, CustomerService>();
            services.AddTransientLazy <IBlogService, BlogService>();
        }