// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();

            services.AddDbContext <DataContext>(options => {
                options.UseSqlServer(Configuration.GetConnectionString("Default"), sqlServerOptions =>
                {
                    sqlServerOptions.MigrationsAssembly($"{typeof(DataContext).Namespace}.SqlServer");
                });
            });

            services.AddTransient <CareerStore>();
            services.AddTransient <MyData>();

            services.AddHealthChecks();

            services.AddCors(options => {
                var defaultPolicy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

                defaultPolicy.Origins.Add("localhost");

                options.AddPolicy("Default", defaultPolicy);
            });
            services.AddControllers();
        }
Esempio 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<safetyContext>(options =>
            //    options.UseSqlite("safety_lite.db")
            //);
            //services.AddEntityFrameworkSqlite().AddDbContext<safetyContext>();
            //// Add framework services.

            //services.AddDbContext<safetyContext>(options =>
            //    options.UseSqlServer(Configuration.GetConnectionString("EASConnection")));

            //services.AddDbContext<safetyContext>(options =>
            //    options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDbContext <safetyContext>(
                options => { options.UseSqlite($"Data Source={_env.ContentRootPath}/safety_lite.db"); });


            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            services.AddMvc();
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddCors(options =>
            //{
            //    // this defines a CORS policy called "default"
            //    options.AddPolicy("AppPolicy", policy =>
            //    {
            //        policy.WithOrigins("http://localhost:44360/")
            //            .AllowAnyHeader()
            //            .AllowAnyMethod()
            //            .AllowCredentials();

            //        policy.WithOrigins("http://localhost:44340/")
            //            .AllowAnyHeader()
            //            .AllowAnyMethod()
            //            .AllowCredentials();
            //    });
            //});

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;
            services.AddCors(x => x.AddPolicy("AppPolicy", policy));
            // Add framework services.
            services.AddMvc();
        }
Esempio n. 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            // Add framework services.
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.Configure <SnakeDataRepositoryConfiguration>(
                Configuration.GetSection("SnakeDataRepository"));

            services.AddScoped <ISnakeDataRepository, SnakeDataRepository>();
        }
Esempio n. 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services
            .AddOptions()
            .AddCors(options => {
                var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();
                policy.Origins.Add("*");
                policy.Headers.Add("*");
                policy.Methods.Add("*");
                policy.SupportsCredentials = true;

                options.AddPolicy("CorsPolicy", policy);
            })
            .AddMvc()
            .AddJsonOptions(options =>
            {
                var settings = options.SerializerSettings;

                settings.ContractResolver  = new CamelCasePropertyNamesContractResolver();
                settings.NullValueHandling = NullValueHandling.Ignore;
                settings.Formatting        = Formatting.Indented;
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("LocalOnly", policy => policy.Requirements.Add(new LocalAuthorizationOnlyRequirement()));
                options.AddPolicy("Admin", policy => policy.Requirements.Add(new GroupAuthorizationRequirement("Admin")));
            });

            services.Configure <MongoDBOptions>(Configuration.GetSection("mongodb"));
            MongoDBConfig.RegisterClassMaps();

            return(IocConfig.RegisterComponents(services));
        }
        public void ConfigureServices(IServiceCollection services)
        {
            var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "damienbodserver.pfx"), "");


            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;
            //services.AddTransient(typeof(IHttpContextAccessor), typeof(HttpContextAccessor));

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddAuthentication(options => {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            });

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority       = "https://localhost:44318/";
                options.ApiSecret       = "dataEventRecordsSecret";
                options.ApiName         = "dataEventRecords";
                options.SupportedTokens = SupportedTokens.Both;
            });


            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthorizeFilter(guestPolicy));
            }).AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.AddScoped <IDataRepository, DataRepository>();
        }
Esempio n. 7
0
        public void ConfigureServices(IServiceCollection services)
        {
            var connection        = Configuration["Production:SqliteConnectionString"];
            var folderForKeyStore = Configuration["Production:KeyStoreFolderWhichIsBacked"];

            var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "damienbodserver.pfx"), "");

            services.AddDbContext <DataEventRecordContext>(options =>
                                                           options.UseSqlite(connection)
                                                           );

            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:44337/";
                options.ApiName   = "dataEventRecords";
                options.ApiSecret = "dataEventRecordsSecret";
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthorizeFilter(guestPolicy));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.AddScoped <IDataEventRecordRepository, DataEventRecordRepository>();
        }
Esempio n. 8
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.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>((options =>
            {
                // Password settings - just for testing use qwerty
                options.Password.RequireDigit = false;
                options.Password.RequiredLength = 4;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = true;
                options.Password.RequiredUniqueChars = 2;
            }))
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                options.ClaimsIdentity.RoleClaimType = "Member";
                options.ClaimsIdentity.RoleClaimType = "Admin";
            });

            services.AddAuthentication();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Account/Manage");
                options.Conventions.AuthorizePage("/Account/Logout");
            })
            .AddJsonOptions(
                options => {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            }
                );

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Zenith Society Bryn Vince", Version = "v1"
                });
            });

            // Register no-op EmailSender used by account confirmation and password reset during development
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            services.AddSingleton <IEmailSender, EmailSender>();
        }
Esempio n. 9
0
        public void ConfigureServices(IServiceCollection services)
        {
            var connection        = Configuration["Production:SqliteConnectionString"];
            var folderForKeyStore = Configuration["Production:KeyStoreFolderWhichIsBacked"];

            var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "damienbodserver.pfx"), "");

            // Important The folderForKeyStore needs to be backed up.
            services.AddDataProtection()
            .SetApplicationName("AspNet5IdentityServerAngularImplicitFlow")
            .PersistKeysToFileSystem(new DirectoryInfo(folderForKeyStore))
            .ProtectKeysWithCertificate(cert);


            services.AddDbContext <DataEventRecordContext>(options =>
                                                           options.UseSqlite(connection)
                                                           );

            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthorizeFilter(guestPolicy));
            }).AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.AddScoped <IDataEventRecordRepository, DataEventRecordRepository>();
        }
Esempio n. 10
0
        private void ConfigureCors(IServiceCollection services)
        {
            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(c => {
                c.AddPolicy("AllowOrigin", policy);
            });
        }
Esempio n. 11
0
        public void ConfigureServices(IServiceCollection services)
        {
            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            //services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));
            services.AddCors();

            var securedFilesPolicy = new AuthorizationPolicyBuilder()
                                     .RequireAuthenticatedUser()
                                     .RequireClaim("scope", "securedFiles")
                                     .Build();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:44318/";
                options.ApiName   = "securedFiles";
                options.ApiSecret = "securedFilesSecret";
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("securedFilesUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "securedFiles.user");
                });
                options.AddPolicy("securedFiles", policyUser =>
                {
                    policyUser.RequireClaim("scope", "securedFiles");
                });
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthorizeFilter(securedFilesPolicy));
            });

            services.AddMvc();

            services.AddTransient <ISecuredFileProvider, SecuredFileProvider>();
            services.AddSingleton <UseOnceAccessIdService>();
        }
Esempio n. 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            services.AddSignalR();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        public void ConfigureServices(IServiceCollection services)
        {
            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            services.AddMvc();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            services.AddMvc();
        }
Esempio 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.AddCors(options =>
            //{
            //    // this defines a CORS policy called "default"
            //    options.AddPolicy("AppPolicy", policy =>
            //    {
            //        policy.WithOrigins("http://localhost:44350/")
            //            .AllowAnyHeader()
            //            .AllowAnyMethod()
            //            .AllowCredentials();

            //        policy.WithOrigins("http://localhost:44340/")
            //            .AllowAnyHeader()
            //            .AllowAnyMethod()
            //            .AllowCredentials();
            //    });
            //});

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;
            services.AddCors(x => x.AddPolicy("AppPolicy", policy));

            // Add framework services.
            services.Configure <DBConnectionSettings>(options =>
            {
                options.ConnectionString = Configuration["DB:Dev:ConnectionString"];
            });
            services.AddScopedFromFactory <MySqlConnection, MySQLConnectionFactory>();
            services.AddScoped(typeof(IService <>), typeof(Service <>));

            services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();

            SqlMapperExtensions.TableNameMapper = (type) =>
            {
                //use exact name
                return(type.Name);
            };
        }
Esempio n. 16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //SqlLite Connection
            services.AddDbContext <texpContext>(
                options => { options.UseSqlite($"Data Source={_env.ContentRootPath}/texp_lite.db"); });


            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            // Add framework services.
            services.AddMvc();
        }
Esempio 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.AddCors();
            services.Configure <UniversidadContext>(Configuration.GetSection("AppSettings"));

            services.AddDbContext <UniversidadContext>(options =>
            {
                options.UseSqlServer(Configuration["AppSettings:ConnectionString"]);
            });

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            // Add framework services.
            services.AddMvc();
        }
Esempio n. 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));

            services.AddDbContext <Server.Models.TESTContext>(options =>
            {
                options.UseSqlServer(Configuration["AppSettings:ConnectionString"]);
                options.UseOpenIddict();
            }).AddDbContext <Server.Models2.TESTResourceContext>(options =>
            {
                options.UseSqlServer(Configuration["AppSettings:ConnectionString2"]);
            });

            services.AddOpenIddict(options =>
            {
                options.AddEntityFrameworkCoreStores <TESTContext>();
                options.AddMvcBinders();
                options.EnableTokenEndpoint("/connect/token");
                options.AllowPasswordFlow().AllowRefreshTokenFlow();
                options.SetAccessTokenLifetime(TimeSpan.FromMinutes(1));
                options.SetRefreshTokenLifetime(TimeSpan.FromMinutes(2));
                options.DisableHttpsRequirement();
                options.UseJsonWebTokens();
                options.AddSigningKey(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["AppSettings:Jwt:SigningKey"])));
            });

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));


            services.AddMvc();
        }
Esempio n. 19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddControllers();
            //services.AddSwaggerGen(c =>
            //{
            //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "oauth_api", Version = "v1" });
            //});

            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(Configuration.GetSection("Secret").Value)),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                };
            });

            services
            .AddAuthContext(Configuration.GetConnectionString("AuthDB"))
            .AddToken(Configuration.GetSection("Secret"))
            .AddCrypto(Configuration.GetSection("HashPassword"));
        }
        public void ConfigureServices(IServiceCollection services)
        {
            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            var securedFilesPolicy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .RequireClaim("scope", "securedFiles")
                .Build();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("securedFilesUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "securedFiles.user");
                });
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthorizeFilter(securedFilesPolicy));
            });

            services.AddMvc();

            services.AddTransient<ISecuredFileProvider, SecuredFileProvider>();
            services.AddSingleton<UseOnceAccessIdService>();
        }
Esempio 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.AddSingleton <IConfigurationRoot>((provider) => Configuration);

            //REPOSITORY
            services.AddScoped <TestDbContext, TestDbContext>();

            //SERVIE
            services.AddScoped <TestService, TestService>();


            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            services.AddMvc();
        }
Esempio n. 22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.Configure<SnakeDataRepositoryConfiguration>(
            Configuration.GetSection("SnakeDataRepository"));

            services.AddScoped<ISnakeDataRepository, SnakeDataRepository>();
        }
Esempio n. 23
0
        public void ConfigureServices(IServiceCollection services)
        {
            //var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "damienbodserver.pfx"), "");

            //services.AddTransient<UserManager<ApplicationUser>>();
            //services.AddTransient<RoleManager<ApplicationRole>>();
            //services.AddTransient<SignInManager<ApplicationRole>>();



            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddStorageCoreDataAccess <ApplicationDbContext>();


            // configure expiring token of  EmailConfirmationToken
            var emailConfirmTokenProviderName          = Configuration.GetSection("TokenProviders").GetSection("EmailConfirmTokenProvider").GetValue <string>("Name");
            var emailConfirmTokenProviderTokenLifespan = Configuration.GetSection("TokenProviders").GetSection("EmailConfirmTokenProvider").GetValue <double>("TokenLifespan");

            services.Configure <IdentityOptions>(options => options.Tokens.EmailConfirmationTokenProvider   = emailConfirmTokenProviderName);
            services.Configure <EmailConfirmProtectorTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromMilliseconds(emailConfirmTokenProviderTokenLifespan));

            services.AddScoped <UserStore <ApplicationUser, ApplicationRole, ApplicationDbContext, Guid, IdentityUserClaim <Guid>, ApplicationUserRole, IdentityUserLogin <Guid>, IdentityUserToken <Guid>, IdentityRoleClaim <Guid> >, ApplicationUserStore>();
            services.AddScoped <UserManager <ApplicationUser>, ApplicationUserManager>();
            services.AddScoped <IUserClaimsPrincipalFactory <ApplicationUser>, ApplicationUserClaimsPrincipalFactory <ApplicationUser, ApplicationRole> >();

            services.AddScoped <ApplicationUserStore, ApplicationUserStore>();
            services.AddScoped <ApplicationUserManager, ApplicationUserManager>();

            services.AddIdentity <ApplicationUser, ApplicationRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 4;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddUserStore <ApplicationUserStore>()
            .AddUserManager <ApplicationUserManager>()
            .AddClaimsPrincipalFactory <ApplicationUserClaimsPrincipalFactory <ApplicationUser, ApplicationRole> >()
            .AddDefaultTokenProviders()
            .AddTokenProvider <EmailConfirmDataProtectorTokenProvider <ApplicationUser> >(emailConfirmTokenProviderName);

            var corsPolicy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            corsPolicy.Headers.Add("*");
            corsPolicy.Methods.Add("*");
            corsPolicy.Origins.Add("*");
            corsPolicy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", corsPolicy));

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();



            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(Resources.GetIdentityResources())
            .AddInMemoryApiResources(Resources.GetApiResources())
            .AddInMemoryClients(Clients.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityProfileService>()
            .AddAuthorizeInteractionResponseGenerator <AccountChooserResponseGenerator>();



            services.AddTransient <IProfileService, IdentityProfileService>();
            services.AddTransient <IExtensionGrantValidator, DelegationGrantValidator>();
            services.AddScoped <IAuthorizationHandler, PermissionHandler>();

            var connectionString = Configuration.GetConnectionString("DefaultConnection");

            services.AddDependencies(Configuration, connectionString);
            SqlConnectionFactory.ConnectionString = connectionString;

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "http://localhost:5050" + "/";
                options.ApiName              = "api2";
                options.ApiSecret            = "secret";
                options.SupportedTokens      = SupportedTokens.Both;
                options.RequireHttpsMetadata = false;
            });

            services.AddAuthorization(options =>
            {
                // Note: It is policy for Authorize atribute
                options.DefaultPolicy = new AuthorizationPolicyBuilder(new[] { JwtBearerDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme })
                                        .RequireAuthenticatedUser()
                                        .Build();
                // Note: Adding permisions as policy
                var permissionList = new List <string>();
                permissionList.AddRange(ClassHelper.GetConstantValues <SystemStaticPermissions.Configs>());
                permissionList.AddRange(ClassHelper.GetConstantValues <SystemStaticPermissions.Users>());
                permissionList.AddRange(ClassHelper.GetConstantValues <SystemStaticPermissions.Groups>());
                foreach (var permission in permissionList)
                {
                    options.AddPolicy(
                        permission,
                        policy => {
                        policy.AddAuthenticationSchemes(new[] { JwtBearerDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme });
                        policy.Requirements.Add(new PermissionRequirement(permission));
                    });
                }
            });

            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });
        }
Esempio n. 24
0
        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddAuthentication();

            SecurityKey signingKey;
            //RSACryptoServiceProvider randomRSA = new RSACryptoServiceProvider(2048);
            //RSAParameters keyParams = randomRSA.ExportParameters(true);
            //signingKey = new RsaSecurityKey(keyParams);
            //services.AddSingleton(new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256));

            signingKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(ServiceConfiguration.SigningKey)); // This could be changed every hour or so
            signingKey.CryptoProviderFactory = new MonoFriendlyCryptoProviderFactory(_LoggerFactory.CreateLogger<MonoFriendlyCryptoProviderFactory>());

            services.AddSingleton(new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256));

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                    .RequireAuthenticatedUser().Build());
            });
            services.Configure<JwtBearerOptions>(options =>
            {
                options.SecurityTokenValidators.Clear();
                options.SecurityTokenValidators.Add(new OrganisationSecurityTokenHandler());
                options.TokenValidationParameters.IssuerSigningKey = signingKey;

                // Basic settings - signing key to validate with, audience and issuer.
                options.TokenValidationParameters.ValidateAudience = false;
                options.TokenValidationParameters.ValidateIssuer = false;
                //options.TokenValidationParameters.ValidAudience = TOKEN_AUDIENCE;
                //options.TokenValidationParameters.ValidIssuer = TOKEN_ISSUER;

                // When receiving a token, check that we've signed it.
                options.TokenValidationParameters.ValidateLifetime = true;

                // Where external tokens are used, some leeway here could be useful.
                options.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(0);

                options.AutomaticAuthenticate = true;
            #if DEBUG
                options.RequireHttpsMetadata = false; // not in prod
            #else
                options.RequireHttpsMetadata = true;
            #endif
            });

            services.AddMvc();
            services.Configure<Microsoft.AspNetCore.Mvc.MvcOptions>(options =>
            {
                options.RespectBrowserAcceptHeader = true;
                options.InputFormatters.Clear();
                options.InputFormatters.Add(new MediaTypeJsonInputFormatter(_LoggerFactory.CreateLogger<MediaTypeJsonInputFormatter>()));
                options.InputFormatters.Add(new MediaTypeXmlSerializerInputFormatter());
                options.OutputFormatters.Clear();
                options.OutputFormatters.Add(new MediaTypeJsonOutputFormatter());
                options.OutputFormatters.Add(new MediaTypeXmlSerializerOutputFormatter());

                // Register filter globally
                options.Filters.Add(new ExceptionResultFilterAttribute(_LoggerFactory.CreateLogger<ExceptionResultFilterAttribute>()));
            });

            #if DEBUG
            services.AddCors();
            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.Configure<Microsoft.AspNetCore.Cors.Infrastructure.CorsOptions>(x => x.AddPolicy("allowEveryThingPolicy", policy));
            #endif
        }
Esempio n. 25
0
        public void ConfigureServices(IServiceCollection services)
        {
            var connection            = Configuration.GetConnectionString("DefaultConnection");
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;

            if (_env.IsProduction())
            {
                if (useLocalCertStore)
                {
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                        cert = certs[0];
                        store.Close();
                    }
                }
                else
                {
                    // Azure deployment, will be used if deployed to Azure
                    var vaultConfigSection = Configuration.GetSection("Vault");
                    var keyVaultService    = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
                    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
                }
            }
            else
            {
                cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "damienbodserver.pfx"), "");
            }

            // Important The folderForKeyStore needs to be backed up.
            // services.AddDataProtection()
            //    .SetApplicationName("ResourceServer")
            //    .PersistKeysToFileSystem(new DirectoryInfo(folderForKeyStore))
            //    .ProtectKeysWithCertificate(cert);

            services.AddDataProtection()
            .SetApplicationName("ResourceServer")
            .ProtectKeysWithCertificate(cert)
            .AddKeyManagementOptions(options =>
                                     options.XmlRepository = new SqlXmlRepository(
                                         new DataProtectionDbContext(
                                             new DbContextOptionsBuilder <DataProtectionDbContext>().UseSqlite(connection).Options
                                             )
                                         )
                                     );

            services.AddDbContext <DataEventRecordContext>(options =>
                                                           options.UseSqlite(connection)
                                                           );

            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:44318/";
                options.ApiName   = "dataEventRecords";
                options.ApiSecret = "dataEventRecordsSecret";
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
                options.AddPolicy("dataEventRecords", policyUser =>
                {
                    policyUser.RequireClaim("scope", "dataEventRecords");
                });
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthorizeFilter(guestPolicy));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.AddScoped <IDataEventRecordRepository, DataEventRecordRepository>();
        }
Esempio n. 26
0
 public CorsMiddleware(Microsoft.AspNetCore.Http.RequestDelegate next, Microsoft.AspNetCore.Cors.Infrastructure.ICorsService corsService, Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy policy, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
 {
 }
Esempio n. 27
0
 public CorsPolicyMetadata(Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy policy)
 {
 }
Esempio n. 28
0
 public virtual void EvaluateRequest(Microsoft.AspNetCore.Http.HttpContext context, Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy policy, Microsoft.AspNetCore.Cors.Infrastructure.CorsResult result)
 {
 }
Esempio n. 29
0
 public Microsoft.AspNetCore.Cors.Infrastructure.CorsResult EvaluatePolicy(Microsoft.AspNetCore.Http.HttpContext context, Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy policy)
 {
     throw null;
 }
Esempio n. 30
0
 public CorsPolicyBuilder(Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy policy)
 {
 }
Esempio n. 31
0
 public void AddPolicy(string name, Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy policy)
 {
 }
Esempio n. 32
0
 public void AddDefaultPolicy(Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy policy)
 {
 }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
            {
                // Configure the context to use Microsoft SQL Server.
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));

                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            });

            // Register the Identity services.
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType   = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType     = OpenIdConnectConstants.Claims.Role;
            });

            // Register the OpenIddict services.
            services.AddOpenIddict(options =>
            {
                // Register the Entity Framework stores.
                options.AddEntityFrameworkCoreStores <ApplicationDbContext>();

                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to
                // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.AddMvcBinders();

                // Enable the authorization, logout, userinfo, and introspection endpoints.
                options.EnableAuthorizationEndpoint("/connect/authorize")
                .EnableLogoutEndpoint("/connect/logout")
                .EnableIntrospectionEndpoint("/connect/introspect")
                .EnableUserinfoEndpoint("/api/userinfo");

                // Note: the sample only uses the implicit code flow but you can enable
                // the other flows if you need to support implicit, password or client credentials.
                options.AllowImplicitFlow();

                // During development, you can disable the HTTPS requirement.
                options.DisableHttpsRequirement();

                // Register a new ephemeral key, that is discarded when the application
                // shuts down. Tokens signed using this key are automatically invalidated.
                // This method should only be used during development.
                options.AddEphemeralSigningKey();

                options.AllowImplicitFlow();

                options.AddSigningCertificate(_cert);

                options.UseJsonWebTokens();
            });

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

            services.AddAuthentication()
            .AddJwtBearer(options =>
            {
                options.Authority                 = "https://localhost:44319/";
                options.Audience                  = "dataEventRecords";
                options.RequireHttpsMetadata      = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = OpenIdConnectConstants.Claims.Name,
                    RoleClaimType = OpenIdConnectConstants.Claims.Role
                };
            });

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

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

            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddTransient <ISmsSender, AuthMessageSender>();
        }
 public static bool IsOriginAnAllowedSubdomain(this Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy policy, string origin)
 {
     throw null;
 }
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = Configuration["Production:SqliteConnectionString"];
            var folderForKeyStore = Configuration["Production:KeyStoreFolderWhichIsBacked"];

            var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "damienbodserver.pfx"), "");

            // Important The folderForKeyStore needs to be backed up.
            services.AddDataProtection()
                .SetApplicationName("AspNet5IdentityServerAngularImplicitFlow")
                .PersistKeysToFileSystem(new DirectoryInfo(folderForKeyStore))
                .ProtectKeysWithCertificate(cert);

            services.AddDbContext<DataEventRecordContext>(options =>
                options.UseSqlite(connection)
            );

            //Add Cors support to the service
            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            var guestPolicy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .RequireClaim("scope", "dataEventRecords")
                .Build();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role",  "dataEventRecords.user");
                });

            });

            services.AddMvc(options =>
            {
               options.Filters.Add(new AuthorizeFilter(guestPolicy));
            }).AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.AddScoped<IDataEventRecordRepository, DataEventRecordRepository>();
        }