Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));

/*            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
 *              .AddEntityFrameworkStores<ApplicationDbContext>();*/

            // Customizes Identity service
            services.AddIdentity <ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

            services.AddAuthorization(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.AddPolicy("MohawkAdmin", policy =>
                {
                    policy.RequireRole("Admin");
                    policy.Requirements.Add(new EmailDomainRequirement("mohawkcollege.ca"));
                });
            });



            services.AddSingleton <IAuthorizationHandler, EmailDomainHandler>();

            services.AddControllersWithViews();
            services.AddRazorPages();
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));
            //services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            //    .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddIdentity <ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

            //Adds Authorization of Email Requirment
            services.AddAuthorization(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.AddPolicy("TeamManagers", policy =>
                {
                    //Must have a role as "Manager"
                    policy.RequireRole("Manager");
                    //Must have an email of "@mohawkcollege.ca"
                    policy.Requirements.Add(new EmailDomainRequirement("mohawkcollege.ca"));
                });
            });
            //Email Authorization at Startuo
            services.AddSingleton <IAuthorizationHandler, EmailDomainHandler>();
            services.AddControllersWithViews();
            services.AddRazorPages();
        }
Ejemplo n.º 3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.ConfigureExceptionHandler();

            app.UseRouting();

            if (env.IsDevelopment())
            {
                app.UseCors(OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            }
            else
            {
                app.UseCors();
            }

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.AddDefaultPolicy(
                    builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
                });
            });

            services.AddScoped <EventoRepositorio>();

            services.AddScoped <ParticipacaoRepositorio>();

            services.AddScoped <CategoriaRepositorio>();

            services.AddScoped <StatusRepositorio>();

            services.AddControllers();

            services.AddSwaggerGen();

            services.AddTransient <EventoService>();

            services.AddTransient <ParticipacaoService>();

            services.AddTransient <CategoriaService>();

            services.AddTransient <StatusService>();
        }
Ejemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddCors(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.AddPolicy("AllowOrigin", builder => builder.WithOrigins("http://localhost:3000"));
            });

            services.AddCors();//api ye dýþarýdan eriþim saðlanabilmesi için gerekli ; nereden eriþilebilecegini belirliyoruz Configure içerisine bak
            var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>();

            //Microsoft.AspNetCore.Authentication.JwtBearer
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidIssuer              = tokenOptions.Issuer,
                    ValidAudience            = tokenOptions.Audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey)
                };
            });

            //ServiceTool.Create(services); //bu satýrýn yerine daha fonksiyonel bir geliþtirme yaptým
            services.AddDependencyResolvers(new ICoreModel[] {
                new CoreModule()
            });

            //Buradaki IoC yerine Manage nuget packages'dan Business katmanýna Autofac ve Autofac.Extras
            //Autofac teknolojisini kuruyoruz "Autofac" ve "Autofac.Extras.DynamicProxy" yi kuruyoruz

            //Autofac,Ninject,CastleWindsor,StructureMap,LightInject,DryInject -->IoC Container için yapýlardýr bunlardan birini kullanacaðýz
            //Postrsharp (ücretli bir IoC)

            //Net.core ile Autofac i kullanabiliriz (bize IoC container altyapýsý sunmakta)
            //Autofac bize AOP imkaný sunmakta ondan dolayý onu kullanacaðýz (2. ek çok kullanýlan Ninject)

            //Biz AOP (Aspect Oriented Programming) yapacaðýz
            //AOP bir methodun önünde, sonunda çalýþan kod parçalýklarýný AOP mimarisi ile vereceðiz

            //Biri constructorda IProductService isterse ProductManager() i new le ve ona ver !!!
            //services.AddSingleton<IProductService, ProductManager>();//Bana arka planda bir referans oluþtur IoC bizim yerine new ler
            //services.AddSingleton<IProductDal, EFProductDal>();

            //services.AddTransient - datalý referanslar için
            //services.AddScoped  - datalý referanslar için
        }
Ejemplo n.º 6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            AddSwagger(services);
            services.AddApplicationSerices();
            services.AddPersistenceServices(Configuration);
            services.AddControllers();

            services.AddCors(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.AddPolicy("Open", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            });
        }
Ejemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <Context>(OptionsBuilderConfigurationExtensions =>
                                            OptionsBuilderConfigurationExtensions.UseSqlServer(Configuration.GetConnectionString("conexao")));
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Ejemplo n.º 8
0
 // This method gets called by the runtime. Use this method to add services to the container.
 //i.e. register stuff here
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <NoteContext>(opt => opt.UseMySql(Configuration.GetConnectionString("WhatIsMyConnectionString")));
     services.AddControllers();
     services.AddCors(OptionsBuilderConfigurationExtensions =>
     {
         OptionsBuilderConfigurationExtensions.AddPolicy(name: MyAllowSpecificOrigins, builder =>
         {
             //builder.WithOrigins("http://localhost:4200","*").AllowAnyHeader().AllowAnyMethod();
             //Note to future self above will only allow localmachine, below will allow any machine/origin
             builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
         });
     });
 }
Ejemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });

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

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }
Ejemplo n.º 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.AddPolicy("Cors", builder =>
            {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));
            services.AddScoped <IUserLogin, UserLoginProvider>();
            //services.AddHttpClient();

            services.AddMvc().AddNewtonsoftJson();

            services.AddControllers();
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(Startup));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            services.AddMvc(option => option.EnableEndpointRouting = false);
            services.AddDbContext <AppDbContext>(OptionsBuilderConfigurationExtensions => {
                OptionsBuilderConfigurationExtensions.UseInMemoryDatabase("supermarket-api-in-memory");
            });

            services.AddScoped <ICategoryRepository, CategoryRepository>();
            services.AddScoped <IProductRepository, ProductRepository>();

            services.AddScoped <ICategoryService, CategoryService>();
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();
        }
Ejemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.AddPolicy("Cors", builder =>
            {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));
            services.AddScoped <IProdutosProvider, ProviderProdutos>();
            services.AddAutoMapper(typeof(Startup));
            //services.AddDbContext<ProdutosDbContext>(options =>
            //{
            //    options.UseInMemoryDatabase("Products");
            //});

            services.AddDbContext <SiteMercadoContext>(options =>
                                                       options.UseSqlServer(
                                                           this.Configuration.GetConnectionString("DefaultProdutos")));


            services.AddControllers();
        }
Ejemplo n.º 13
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <StudentContext>(OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.UseSqlite("Data source=Student.db"));
     services.AddControllers();
 }
Ejemplo n.º 14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultForbidScheme       = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer()
            .AddJwtBearer("CustomerAuth", options =>
            {
                options.Authority = Configuration.GetValue <string>("CustomerAuthServerUrl");
                options.Audience  = "review_api";
            })
            .AddJwtBearer("StaffAuth", options =>
            {
                options.Authority = Configuration.GetValue <string>("StaffAuthServerUrl");
                options.Audience  = "review_api";
            });

            services.AddAuthorization(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.DefaultPolicy = new AuthorizationPolicyBuilder()
                                                                      .RequireAuthenticatedUser()
                                                                      .AddAuthenticationSchemes("CustomerAuth")
                                                                      .Build();

                OptionsBuilderConfigurationExtensions.AddPolicy("OrderingAPIOnly", policy =>
                                                                policy.AddAuthenticationSchemes("CustomerAuth")
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_ordering_api"))
                                                                .Build());

                OptionsBuilderConfigurationExtensions.AddPolicy("CustomerAccountAPIOnly", policy =>
                                                                policy.AddAuthenticationSchemes("CustomerAuth")
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_account_api"))
                                                                .Build());

                OptionsBuilderConfigurationExtensions.AddPolicy("CustomerOnly", policy =>
                                                                policy.AddAuthenticationSchemes("CustomerAuth")
                                                                .RequireAuthenticatedUser()
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_web_app"))
                                                                .Build());

                OptionsBuilderConfigurationExtensions.AddPolicy("StaffOnly", policy =>
                                                                policy.AddAuthenticationSchemes("StaffAuth")
                                                                //.RequireAuthenticatedUser()
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_management_web_app"))
                                                                .Build());
            });

            services.AddControllers();
            services.AddAutoMapper(typeof(Startup));
            services.AddDbContext <ReviewDb>(options =>
            {
                var cs = Configuration.GetConnectionString("ReviewConnection");
                options.UseSqlServer(cs);
            });
            services.AddScoped <IReviewRepository, ReviewRepository.ReviewRepository>();
        }
Ejemplo n.º 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.UseInMemoryDatabase("StorageDB"));
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Backend", Version = "v1"
                });
            });

            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder
                .SetIsOriginAllowed(_ => true)
                .AllowCredentials()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));
        }
Ejemplo n.º 16
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <ApplicationDbContext>(OptionsBuilderConfigurationExtensions =>
                                                  OptionsBuilderConfigurationExtensions.UseSqlServer(
                                                      Configuration.GetConnectionString("DefaultConnection")));
 }
Ejemplo n.º 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(opt =>
            {
                opt.UseLazyLoadingProxies();
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000").AllowCredentials();
                });
            });
            services.AddMediatR(typeof(List.Handler).Assembly);
            services.AddAutoMapper(typeof(List.Handler).Assembly);
            services.AddSignalR();
            services.AddMvc(opt =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddFluentValidation(cfg =>
                                 cfg.RegisterValidatorsFromAssemblyContaining <Create>())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var builder         = services.AddIdentityCore <AppUser>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

            identityBuilder.AddEntityFrameworkStores <DataContext>();
            identityBuilder.AddSignInManager <SignInManager <AppUser> >();

            services.AddAuthorization(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.AddPolicy("IsActivityHost", policy =>
                {
                    policy.Requirements.Add(new IsHostRequirement());
                });
            });

            services.AddTransient <IAuthorizationHandler, IsHostRequirementHandler>();

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateAudience         = false,
                    ValidateIssuer           = false
                };
                opt.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path        = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/chat"))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IUserAccessor, UserAccessor>();
            services.AddScoped <IPhotoAccessor, PhotoAccessor>();
            services.AddScoped <IProfileReader, ProfileReader>();
            services.Configure <CloudinarySettings>(Configuration.GetSection("Cloudinary"));
        }
        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultForbidScheme       = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer()
            .AddJwtBearer("ProductAuth", options =>
            {
                options.Authority = Configuration.GetValue <string>("StaffAuthServerUrl");
                options.Audience  = "customer_product_api";
            })
            .AddJwtBearer("CustomerAuth", options =>
            {
                options.Authority = Configuration.GetValue <string>("CustomerAuthServerUrl");
                options.Audience  = "customer_product_api";
            });

            services.AddAuthorization(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.DefaultPolicy = new AuthorizationPolicyBuilder()
                                                                      .RequireAuthenticatedUser()
                                                                      .AddAuthenticationSchemes("ProductAuth")
                                                                      .Build();
                OptionsBuilderConfigurationExtensions.AddPolicy("CustomerOnly", new AuthorizationPolicyBuilder()
                                                                .RequireAuthenticatedUser()
                                                                .AddAuthenticationSchemes("CustomerAuth")
                                                                .Build());
                OptionsBuilderConfigurationExtensions.AddPolicy("StaffProductAPIOnly", new AuthorizationPolicyBuilder()
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "staff_product_api"))
                                                                .AddAuthenticationSchemes("ProductAuth")
                                                                .Build());
            });


            services.AddControllers();
            services.AddAutoMapper(typeof(Startup));
            services.AddDbContext <ProductDb>(options =>
            {
                var cs = Configuration.GetConnectionString("ProductConnection");
                options.UseSqlServer(cs);
            });

            services.AddScoped <IProductRepository, ProductRepository.ProductRepository>();
            services.AddScoped <IHttpHandler, HttpHandler>();
            services.AddScoped <IUnmockablesWrapper, UnmockablesWrapper>();

            services.AddSingleton(new ClientCredentialsTokenRequest
            {
                Address      = "",
                ClientId     = Configuration.GetValue <string>("ClientId"),
                ClientSecret = Configuration.GetValue <string>("ClientSecret"),
                Scope        = ""
            });

            if (Env.IsDevelopment())
            {
                services.AddScoped <IProductOrderFacade, ProductOrderFacade.FakeProductOrderFacade>();
            }
            else
            {
                services.AddScoped <IProductOrderFacade, ProductOrderFacade.ProductOrderFacade>();
            }

            services.AddHttpClient("CustomerOrderingAPI", client =>
            {
                client.BaseAddress = new Uri(Configuration.GetSection("CustomerOrderingUrl").Value);
            })
            .AddTransientHttpErrorPolicy(p => p.OrResult(
                                             msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
                                         .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
            .AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(60)));
        }
Ejemplo n.º 19
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <BigProjectContext>(OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.UseMySql(Configuration["DBInfo:ConnectionString"]));
     services.AddSession();
     services.AddMvc();
 }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(Startup));
            // configure EF context to use for storing Identity account data
            services.AddDbContext <AccountDbContext>(options => options.UseSqlServer(
                                                         Configuration.GetConnectionString("AccountConnection"), optionsBuilder =>
            {
                optionsBuilder.EnableRetryOnFailure(10, TimeSpan.FromSeconds(10), null);
            }));

            // configure Identity account management
            services.AddIdentity <AppUser, AppRole>()
            .AddEntityFrameworkStores <AccountDbContext>()
            .AddDefaultTokenProviders();
            IdentityModelEventSource.ShowPII = true;

            // add bespoke factory to translate our AppUser into claims
            services.AddScoped <IUserClaimsPrincipalFactory <AppUser>, AppClaimsPrincipalFactory>();
            services.AddScoped <IRepository, Repository>();

            // configure Identity security options
            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 8;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase       = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequiredUniqueChars    = 6;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(10);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings
                options.User.RequireUniqueEmail = true;

                // Sign-in settings
                options.SignIn.RequireConfirmedEmail = false;
            });

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultForbidScheme       = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer()
            .AddJwtBearer("customer_web_app", options =>
            {
                options.Audience  = "customer_auth_customer_api";
                options.Authority = Configuration.GetValue <string>("CustomerAuthServerUrl");
            })
            .AddJwtBearer("customer_account_api", options =>
            {
                options.Audience  = "customer_auth_staff_api";
                options.Authority = Configuration.GetValue <string>("CustomerAuthServerUrl");
            });


            services.AddAuthorization(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.DefaultPolicy = new AuthorizationPolicyBuilder()
                                                                      .RequireAuthenticatedUser()
                                                                      .AddAuthenticationSchemes("customer_web_app", "customer_account_api")
                                                                      .Build();

                OptionsBuilderConfigurationExtensions.AddPolicy("customer_web_app_only", policy =>
                                                                policy.AddAuthenticationSchemes("customer_web_app")
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_web_app")
                                                                                  ));

                OptionsBuilderConfigurationExtensions.AddPolicy("user_exists_only", policy =>
                                                                policy.AddAuthenticationSchemes("customer_web_app")
                                                                .RequireAssertion(context =>
                                                                                  (context.User.HasClaim(c => c.Type == "role" && c.Value == "Customer") &&
                                                                                   context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_web_app")) ||
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_account_api")
                                                                                  ));
            });

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

            // configure IdentityServer (provides OpenId Connect and OAuth2)
            if (Env.IsDevelopment())
            {
                services.AddIdentityServer()
                .AddInMemoryIdentityResources(Configuration.GetIdentityResources())
                .AddInMemoryApiResources(Configuration.GetIdentityApis())
                .AddInMemoryClients(Configuration.GetIdentityClients())
                .AddAspNetIdentity <AppUser>()
                .AddDeveloperSigningCredential();
            }
            else
            {
                services.AddIdentityServer()
                .AddInMemoryIdentityResources(Configuration.GetIdentityResources())
                .AddInMemoryApiResources(Configuration.GetIdentityApis())
                .AddInMemoryClients(Configuration.GetIdentityClients())
                .AddAspNetIdentity <AppUser>()
                .AddDeveloperSigningCredential();
            }

            // TODO: developer signing cert above should be replaced with a real one
            // TODO: should use AddOperationalStore to persist tokens between app executions
        }
Ejemplo n.º 21
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllers();
     services.AddSwaggerGen(c =>
     {
         c.SwaggerDoc("v1", new OpenApiInfo {
             Title = "Notely Rest Api", Version = "v1"
         });
     });
     services.AddDbContext <NotelyDbContext>(OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.UseSqlite(Configuration["Data:NotelyRestApi:ConnectionString"]));
     services.AddTransient <INoteRepository, NoteRepository>();
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Méthode permettant d'ajouter des services au conteneur de l'API
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <MyAirportContext>(OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyAirport;Integrated Security=True"));
            services.AddControllers().AddNewtonsoftJson(o =>
            {
                o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "MyAirportApi",
                    Description    = "Gestionnaire d'aéroport",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact        = new OpenApiContact
                    {
                        Name  = "Manuela CALVO & Sophie PAGES",
                        Email = string.Empty,
                        Url   = new Uri("https://twitter.com/spboyer"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url  = new Uri("https://example.com/license"),
                    }
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);


                var referencedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
                referencedAssemblies.ToList().ForEach(assembly =>
                {
                    var path = Path.Combine(AppContext.BaseDirectory, $"{assembly.Name}.xml");
                    if (File.Exists(path))
                    {
                        c.IncludeXmlComments(path);
                    }
                });
            });
        }
Ejemplo n.º 23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            //services.AddAuthentication()
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultForbidScheme       = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer()
            .AddJwtBearer("CustomerAuth", options =>
            {
                options.Authority = Configuration.GetValue <string>("CustomerAuthServerUrl");
                options.Audience  = "customer_ordering_api";
            })
            .AddJwtBearer("StaffAuth", options =>
            {
                options.Authority = Configuration.GetValue <string>("StaffAuthServerUrl");
                options.Audience  = "customer_ordering_api";
            });

            services.AddAuthorization(OptionsBuilderConfigurationExtensions =>
            {
                OptionsBuilderConfigurationExtensions.DefaultPolicy = new AuthorizationPolicyBuilder()
                                                                      .RequireAuthenticatedUser()
                                                                      .AddAuthenticationSchemes("CustomerAuth", "StaffAuth")
                                                                      .Build();

                OptionsBuilderConfigurationExtensions.AddPolicy("CustomerOrAccountAPI", policy =>
                                                                policy.AddAuthenticationSchemes("CustomerAuth")
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "role" && c.Value == "Customer") ||
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_account_api"))
                                                                .Build());

                OptionsBuilderConfigurationExtensions.AddPolicy("CustomerAccountAPIOnly", policy =>
                                                                policy.AddAuthenticationSchemes("CustomerAuth")
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_account_api"))
                                                                .Build());

                OptionsBuilderConfigurationExtensions.AddPolicy("CustomerOrStaffWebApp", policy =>
                                                                policy.AddAuthenticationSchemes("CustomerAuth", "StaffAuth")
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "role" && c.Value == "Customer") ||
                                                                                  context.User.HasClaim(c => c.Type == "role" && c.Value == "Customer Account Manager") ||
                                                                                  context.User.HasClaim(c => c.Type == "role" && c.Value == "Order Manager"))
                                                                .Build());

                OptionsBuilderConfigurationExtensions.AddPolicy("CustomerOnly", policy =>
                                                                policy.AddAuthenticationSchemes("CustomerAuth")
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "role" && c.Value == "Customer"))
                                                                .Build());

                OptionsBuilderConfigurationExtensions.AddPolicy("CustomerProductAPI", policy =>
                                                                policy.AddAuthenticationSchemes("CustomerAuth")
                                                                .RequireAssertion(context =>
                                                                                  context.User.HasClaim(c => c.Type == "client_id" && c.Value == "customer_product_api"))
                                                                .Build());
            });

            services.AddControllers();
            services.AddAutoMapper(typeof(Startup));
            services.AddDbContext <OrderDb>(options => options.UseSqlServer(
                                                Configuration.GetConnectionString("CustomerOrdering"), optionsBuilder =>
            {
                optionsBuilder.EnableRetryOnFailure(10, TimeSpan.FromSeconds(10), null);
            }
                                                ));


            services.AddScoped <IOrderRepository, OrderRepository>();

            if (Env.IsDevelopment())
            {
                services.AddScoped <IStaffProductFacade, FakeStaffProductFacade>();
                services.AddScoped <ICustomerAccountFacade, FakeCustomerFacade>();
                services.AddScoped <IInvoiceFacade, FakeInvoiceFacade>();
                services.AddScoped <IReviewFacade, FakeReviewFacade>();
            }
            else
            {
                services.AddScoped <IStaffProductFacade, StaffProductFacade>();
                services.AddScoped <ICustomerAccountFacade, CustomerFacade>();
                services.AddScoped <IInvoiceFacade, InvoiceFacade>();
                services.AddScoped <IReviewFacade, ReviewFacade>();
            }

            services.AddScoped <IHttpHandler, HttpHandler>();
            services.AddScoped <IUnmockablesWrapper, UnmockablesWrapper>();

            services.AddSingleton(new ClientCredentialsTokenRequest
            {
                Address      = "",
                ClientId     = Configuration.GetValue <string>("ClientId"),
                ClientSecret = Configuration.GetValue <string>("ClientSecret"),
                Scope        = ""
            });


            services.AddHttpClient("CustomerAccountAPI", client =>
            {
                client.BaseAddress = new Uri(Configuration.GetSection("CustomerAccountUrl").Value);
            })
            .AddTransientHttpErrorPolicy(p => p.OrResult(
                                             msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
                                         .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
            .AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(60)));

            services.AddHttpClient("InvoiceAPI", client =>
            {
                client.BaseAddress = new Uri(Configuration.GetSection("InvoiceUrl").Value);
            })
            .AddTransientHttpErrorPolicy(p => p.OrResult(
                                             msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
                                         .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
            .AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(60)));

            services.AddHttpClient("StaffProductAPI", client =>
            {
                client.BaseAddress = new Uri(Configuration.GetSection("StaffProductUrl").Value);
            })
            .AddTransientHttpErrorPolicy(p => p.OrResult(
                                             msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
                                         .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
            .AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(60)));

            services.AddHttpClient("ReviewAPI", client =>
            {
                client.BaseAddress = new Uri(Configuration.GetSection("ReviewUrl").Value);
            })
            .AddTransientHttpErrorPolicy(p => p.OrResult(
                                             msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
                                         .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
            .AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(60)));
        }
Ejemplo n.º 24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext <ApplicationDbContext>(OptionsBuilderConfigurationExtensions => OptionsBuilderConfigurationExtensions.UseSqlServer(Configuration["DefaultConnection"]));

            services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        }