// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ServiceInjection.Register(new List <Assembly>() { Assembly.GetExecutingAssembly() }); services.AddServiceInjection(); services.AddSingleton(new ReviewCategorizer(Settings.Instance.CategorizerModelPath)); services.AddSingleton(new ReviewSentimentAnalyzer(Settings.Instance.SentimentAnalyzerModelPath)); services.AddControllers(options => { options.RespectBrowserAcceptHeader = true; }).AddXmlSerializerFormatters() .AddNewtonsoftJson(); services.AddSwaggerGenNewtonsoftSupport(); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "My API", Description = "A simple example ASP.NET Core Web API", TermsOfService = new Uri("https://example.com/terms"), }); }); }
private static void InitDI(IServiceCollection services) { services.AddScoped <DataContext>() .AddScoped <DbContext>(p => p.GetRequiredService <DataContext>()); ServiceInjection.Register(new List <Assembly>() { Assembly.GetExecutingAssembly() }); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); NinjectModule module = new ServiceInjection(); var kernel = new StandardKernel(module); DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel)); }
public void SetUp() { var services = new ServiceCollection(); services.AddServiceInjection(); ServiceInjection.Register(new List <Assembly>() { Assembly.GetAssembly(typeof(WebApi.Startup)) }); services.AddScoped <UsersController>(); // mocks _validModel = new AuthorizationGrantModel { username = "******", password = "******", }; _invalidModel = new AuthorizationGrantModel { username = "******", password = DateTime.Now.ToString(), }; _anonymous = new ClaimsPrincipal(); var identityServiceMock = new Mock <IIdentityService>(); identityServiceMock.Setup(o => o.ValidateLogin(It.IsAny <ClaimsPrincipal>(), It.IsAny <AuthorizationGrantModel>())) .Returns(new ValidationData()); identityServiceMock.Setup(o => o.AuthenticateAsync( It.Is <string>(u => u == _validModel.username), It.Is <string>(p => p == _validModel.password))) .Returns(Task.FromResult(new AppUser())); identityServiceMock.Setup(o => o.GetIdentityAsync(It.IsAny <AppUser>(), It.IsAny <string>())) .Returns(Task.FromResult(new ClaimsIdentity())); identityServiceMock.Setup(o => o.GenerateTokenResponse(It.IsAny <ClaimsPrincipal>(), It.IsAny <AuthenticationProperties>(), It.IsAny <string>())) .Returns(new TokenResponseModel()); var dbContextMock = Mock.Of <DbContext>(); services.AddScoped(p => identityServiceMock.Object); services.AddScoped(p => dbContextMock); _provider = services.BuildServiceProvider(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var serviceCollection = ServiceInjection.ConfigureServices(); foreach (var service in serviceCollection) { services.Add(service); } services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "RestAPI_NoSQL.WebApi", Version = "v1" }); }); }
private static void InitDI(IServiceCollection services) { ServiceInjection.Register(new List <Assembly>() { Assembly.GetExecutingAssembly() }); //extra var baseServiceType = typeof(Service); var serviceTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(t => t.GetTypes()) .Where(t => baseServiceType.IsAssignableFrom(t) && t.IsClass && !t.IsAbstract); foreach (var t in serviceTypes) { services.AddScoped(t); } }
public void ConfigureServices(IServiceCollection services) { services.Configure <Keys>(Configuration.GetSection("Keys")); var settings = new Keys(); Configuration.GetSection("Keys").Bind(settings); services .AddAuthentication(options => { options.DefaultAuthenticateScheme = "Jwt"; options.DefaultChallengeScheme = "Jwt"; }) .AddJwtBearer("Jwt", options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JwtKey)), ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(60) }; }); RollbarConfigure.ConfigureServices(settings); services.AddRollbarLogger(loggerOptions => { loggerOptions.Filter = (loggerName, loglevel) => loglevel >= LogLevel.Trace; }); services.AddCors(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <AuthFilter>(); services.AddControllers(); ServiceInjection.ConfigureServices(services); if (!Hosting.IsDevelopment()) { services.AddHttpsRedirection(options => { options.HttpsPort = 443; }); } }
public void Setup() { var services = new ServiceCollection(); services.AddServiceInjection(); ServiceInjection.Register(new List <Assembly>() { Assembly.GetAssembly(typeof(Business.Global)) }); Business.Global.Init(services); _createResourceModel = new CreateResourceModel { Name = "Test resource" }; services.AddDbContext <DataContext>(options => options.UseInMemoryDatabase(databaseName: "FQCSDevice")); _provider = services.BuildServiceProvider(); }
private static void ConfigureIoC(IServiceCollection services) { //IoC services.AddScoped <UnitOfWork>() .AddScoped <IUnitOfWork, UnitOfWork>() .AddScoped <DbContext, WorkContext>() .AddScoped <IAspNetRoleClaimsRepository, AspNetRoleClaimsRepository>() .AddScoped <IAspNetRolesRepository, AspNetRolesRepository>() .AddScoped <IAspNetUserClaimsRepository, AspNetUserClaimsRepository>() .AddScoped <IAspNetUserLoginsRepository, AspNetUserLoginsRepository>() .AddScoped <IAspNetUserRolesRepository, AspNetUserRolesRepository>() .AddScoped <IAspNetUserTokensRepository, AspNetUserTokensRepository>() .AddScoped <IAspNetUsersRepository, AspNetUsersRepository>() .AddScoped <IEventsRepository, EventsRepository>() .AddScoped <IGroupUsersRepository, GroupUsersRepository>() .AddScoped <IGroupsRepository, GroupsRepository>() .AddScoped <ILogsRepository, LogsRepository>() .AddScoped <IProductsRepository, ProductsRepository>() .AddScoped <ITasksRepository, TasksRepository>(); ServiceInjection.Register(new List <Type>() { typeof(G) }); }
public ProductionLineService(ServiceInjection inj) : base(inj) { }
public ScheduleDetailService(ServiceInjection inj) : base(inj) { }
public ProductModelService(ServiceInjection inj) : base(inj) { }
public ProductionBatchService(ServiceInjection inj) : base(inj) { }
public FileService(ServiceInjection inj) : base(inj) { }
public AreaService(ServiceInjection inj) : base(inj) { }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile(Settings.Instance.FirebaseCredentials), }); ServiceInjection.Register(new List <Assembly>() { Assembly.GetExecutingAssembly() }); services.AddServiceInjection(); var connStr = Configuration.GetConnectionString("DataContext"); #if TEST connStr = connStr.Replace("{envConfig}", ".Test"); #else connStr = connStr.Replace("{envConfig}", ""); #endif services.AddDbContext <DataContext>(options => options.UseSqlServer(connStr).UseLazyLoadingProxies()); Data.Global.Init(services); var fapSecret = File.ReadAllText(Settings.Instance.FapSecretFile); Business.Global.Init(services, fapSecret); #region OAuth services.AddIdentity <AppUser, AppRole>(options => { options.SignIn.RequireConfirmedEmail = false; }) .AddEntityFrameworkStores <DataContext>(); services.Configure <IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 6; options.Password.RequiredUniqueChars = 0; options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; options.Lockout.AllowedForNewUsers = true; options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = false; }); //required services.AddAuthentication() .AddJwtBearer(jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = JWT.ISSUER, ValidAudience = JWT.AUDIENCE, IssuerSigningKey = new SymmetricSecurityKey( Encoding.Default.GetBytes(JWT.SECRET_KEY)), ClockSkew = TimeSpan.Zero }; //jwtBearerOptions.Events = new JwtBearerEvents //{ // OnMessageReceived = (context) => // { // return Task.CompletedTask; // //StringValues values; // //if (!context.Request.Query.TryGetValue("access_token", out values)) // // return Task.CompletedTask; // //var token = values.FirstOrDefault(); // //context.Token = token; // //return Task.CompletedTask; // } //}; }); #endregion services.ConfigureApplicationCookie(options => { options.Cookie.HttpOnly = true; options.AccessDeniedPath = Routing.ACCESS_DENIED; options.ExpireTimeSpan = TimeSpan.FromHours( WebAdmin.Settings.Instance.CookiePersistentHours); options.LoginPath = Routing.LOGIN; options.LogoutPath = Routing.LOGOUT; options.ReturnUrlParameter = "return_url"; options.SlidingExpiration = true; options.Events.OnValidatePrincipal = async(c) => { var identity = c.Principal.Identity as ClaimsIdentity; //extra claims will be expired after amount of time if (identity.FindFirst(AppClaimType.UserName)?.Value == null) { var identityService = c.HttpContext.RequestServices.GetRequiredService <IdentityService>(); var entity = await identityService.GetUserByUserNameAsync(identity.Name); var principal = await identityService.GetApplicationPrincipalAsync(entity); c.ReplacePrincipal(principal); c.ShouldRenew = true; } await SecurityStampValidator.ValidatePrincipalAsync(c); }; }); services.AddScoped <Layout>(); services.AddSingleton(new DefaultDateTimeModelBinder()); services.AddControllers(options => { options.ModelBinderProviders.Insert(0, new QueryObjectModelBinderProvider()); }).AddNewtonsoftJson(); services.AddRazorPages(options => { var allowAnnonymousPages = new[] { "/AccessDenied", "/Error", "/Status", "/Identity/Login", "/Identity/Register" }; var authorizeFolders = new[] { "/" }; foreach (var f in authorizeFolders) { options.Conventions.AuthorizeFolder(f); } foreach (var p in allowAnnonymousPages) { options.Conventions.AllowAnonymousToPage(p); } }); }
public Service(ServiceInjection inj) { inj.Inject(this); }
public ResourceService(ServiceInjection inj) : base(inj) { }
public DepartmentService(ServiceInjection inj) : base(inj) { }
public MemberService(ServiceInjection inj) : base(inj) { }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ServiceInjection.Register(new List <Assembly>() { Assembly.GetExecutingAssembly() }); services.AddServiceInjection(); var connStr = Configuration.GetConnectionString("DataContext"); #if TEST connStr = connStr.Replace("{envConfig}", ".Test"); #else connStr = connStr.Replace("{envConfig}", ""); #endif services.AddDbContext <DataContext>(options => { options.UseSqlServer(connStr); }); Data.Global.Init(services); Business.Global.Init(services); #region OAuth //for some default Identity configuration services.AddIdentity <AppUser, AppRole>(options => { options.SignIn.RequireConfirmedEmail = false; }) .AddEntityFrameworkStores <DataContext>(); services.Configure <IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 6; options.Password.RequiredUniqueChars = 0; options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; options.Lockout.AllowedForNewUsers = true; options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = false; }); #endregion services.ConfigureApplicationCookie(options => { options.Cookie.HttpOnly = true; options.AccessDeniedPath = Routing.ACCESS_DENIED; options.ExpireTimeSpan = TimeSpan.FromHours( WebAdmin.Settings.Instance.CookiePersistentHours); options.LoginPath = Routing.LOGIN; options.LogoutPath = Routing.LOGOUT; options.ReturnUrlParameter = "return_url"; options.SlidingExpiration = true; options.Events.OnValidatePrincipal = async(c) => { var identity = c.Principal.Identity as ClaimsIdentity; //extra claims will be expired after amount of time if (identity.FindFirst(AppClaimType.UserName)?.Value == null) { var identityService = c.HttpContext.RequestServices.GetRequiredService <IdentityService>(); var entity = await identityService.GetUserByUserNameAsync(identity.Name); var extraClaims = identityService.GetExtraClaims(entity); identity.AddClaims(extraClaims); c.ShouldRenew = true; } await SecurityStampValidator.ValidatePrincipalAsync(c); }; }); services.AddControllers(); services.AddRazorPages(options => { var allowAnnonymousPages = new[] { "/AccessDenied", "/Error", "/Status", "/Identity/Login", #if DEBUG "/Identity/Register" #endif }; var authorizeFolders = new[] { "/" }; var authorizeLocationFolders = new[] { "/" }; options.Conventions .AddAreaPageRoute("Location", "/Dashboard/Index", Routing.LOCATION_DASHBOARD) .AddAreaPageRoute("Location", "/Resource/Index", Routing.LOCATION_RESOURCE) .AddAreaPageRoute("Location", "/Resource/Create", Routing.LOCATION_RESOURCE_CREATE) .AddAreaPageRoute("Location", "/Post/Index", Routing.LOCATION_POST) .AddAreaPageRoute("Location", "/Post/Detail", Routing.LOCATION_POST_DETAIL) .AddAreaPageRoute("Location", "/Post/Create", Routing.LOCATION_POST_CREATE) .AddAreaPageRoute("Location", "/Building/Index", Routing.LOCATION_BUILDING) .AddAreaPageRoute("Location", "/Building/Create", Routing.LOCATION_BUILDING_CREATE) .AddAreaPageRoute("Location", "/Floor/Index", Routing.LOCATION_FLOOR) .AddAreaPageRoute("Location", "/Floor/Create", Routing.LOCATION_FLOOR_CREATE) .AddAreaPageRoute("Location", "/Floor/Detail", Routing.LOCATION_FLOOR_DETAIL) .AddAreaPageRoute("Location", "/Area/Index", Routing.LOCATION_AREA) .AddAreaPageRoute("Location", "/Area/Create", Routing.LOCATION_AREA_CREATE) .AddAreaPageRoute("Location", "/Device/Index", Routing.LOCATION_DEVICE) .AddAreaPageRoute("Location", "/Config/Index", Routing.LOCATION_CONFIG) .AddAreaPageRoute("Location", "/Config/Create", Routing.LOCATION_CONFIG_CREATE) .AddAreaPageRoute("Location", "/Config/Detail", Routing.LOCATION_CONFIG_DETAIL) .AddAreaPageRoute("Location", "/Config/ScreenSaver", Routing.LOCATION_CONFIG_SSP) .AddAreaPageRoute("Location", "/Config/Overview", Routing.LOCATION_CONFIG_OVERVIEW) .AddAreaPageRoute("Location", "/Config/Contact", Routing.LOCATION_CONFIG_CONTACT) .AddAreaPageRoute("Location", "/Schedule/Index", Routing.LOCATION_SCHEDULE) .AddAreaPageRoute("Location", "/Schedule/Create", Routing.LOCATION_SCHEDULE_CREATE) .AddAreaPageRoute("Location", "/Schedule/Detail", Routing.LOCATION_SCHEDULE_DETAIL) .AddAreaPageRoute("Location", "/Schedule/ScheduleDetail", Routing.LOCATION_S_DETAIL_DETAIL) .AddPageRoute("/Post/Detail", Routing.POST_DETAIL) .AddPageRoute("/ResType/Detail", Routing.RES_TYPE_DETAIL) .AddPageRoute("/EtCate/Detail", Routing.ENTITY_CATE_DETAIL) .AddPageRoute("/Owner/Detail", Routing.OWNER_DETAIL); foreach (var f in authorizeFolders) { options.Conventions.AuthorizeFolder(f); } foreach (var f in authorizeLocationFolders) { options.Conventions.AuthorizeAreaFolder("Location", f); } foreach (var p in allowAnnonymousPages) { options.Conventions.AllowAnonymousToPage(p); } }); }
public AuthUserAuthHandler(ServiceInjection inj) : base(inj) { }
public LocationService(ServiceInjection inj) : base(inj) { }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { _services = services; ServiceInjection.Register(new List <Assembly>() { Assembly.GetExecutingAssembly() }); services.AddServiceInjection(); ConnStr = Configuration.GetConnectionString("DataContext"); #if TEST ConnStr = ConnStr.Replace("{envConfig}", ".Test"); #else ConnStr = ConnStr.Replace("{envConfig}", ""); #endif services.AddDbContext <DataContext>(options => options.UseSqlServer(ConnStr).UseLazyLoadingProxies()); services.Configure <ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; }); Data.Global.Init(services); Business.Global.Init(services); #region OAuth services.AddIdentityCore <AppUser>(options => { options.SignIn.RequireConfirmedEmail = false; }).AddRoles <AppRole>() .AddDefaultTokenProviders() .AddSignInManager() .AddEntityFrameworkStores <DataContext>(); services.Configure <IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 6; options.Password.RequiredUniqueChars = 0; options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; options.Lockout.AllowedForNewUsers = true; options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = false; }); //required services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Business.Constants.JWT.ISSUER, ValidAudience = Business.Constants.JWT.AUDIENCE, IssuerSigningKey = new SymmetricSecurityKey( Encoding.Default.GetBytes(Business.Constants.JWT.SECRET_KEY)), ClockSkew = TimeSpan.Zero }; //jwtBearerOptions.Events = new JwtBearerEvents //{ // OnMessageReceived = (context) => // { // StringValues values; // if (!context.Request.Query.TryGetValue("access_token", out values)) // return Task.CompletedTask; // var token = values.FirstOrDefault(); // context.Token = token; // return Task.CompletedTask; // } //}; }); services.AddAuthorization(options => { options.AddPolicy(Constants.Policy.And.APP_CLIENT, policy => policy.Requirements.Add(new AppClientRequirement(isOR: false))); options.AddPolicy(Constants.Policy.Or.APP_CLIENT, policy => policy.Requirements.Add(new AppClientRequirement(isOR: true))); options.AddPolicy(Constants.Policy.And.AUTH_USER, policy => policy.Requirements.Add(new AuthUserRequirement(isOR: false))); options.AddPolicy(Constants.Policy.Or.AUTH_USER, policy => policy.Requirements.Add(new AuthUserRequirement(isOR: true))); options.AddPolicy(Constants.Policy.And.ADMIN_USER, policy => policy.Requirements.Add(new AuthUserRequirement(isOR: false, role: Data.Constants.RoleName.ADMIN))); options.AddPolicy(Constants.Policy.Or.ADMIN_USER, policy => policy.Requirements.Add(new AuthUserRequirement(isOR: true, role: Data.Constants.RoleName.ADMIN))); }); services.AddScoped <IAuthorizationHandler, AppClientAuthHandler>(); services.AddScoped <IAuthorizationHandler, AuthUserAuthHandler>(); #endregion services.AddSingleton(new DefaultDateTimeModelBinder()); services.AddControllers(options => { options.ModelBinderProviders.Insert(0, new QueryObjectModelBinderProvider()); }).AddNewtonsoftJson(); services.AddSwaggerGenNewtonsoftSupport(); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "My API", Description = "A simple example ASP.NET Core Web API", TermsOfService = new Uri("https://example.com/terms"), }); c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Please enter into field the word 'Bearer' following by space and JWT", Name = "Authorization", Type = SecuritySchemeType.ApiKey }); var requirement = new OpenApiSecurityRequirement(); requirement[new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = JwtBearerDefaults.AuthenticationScheme } }] = new string[] { }; c.AddSecurityRequirement(requirement); }); }
public AppEventService(ServiceInjection inj) : base(inj) { }
public AppConfigService(ServiceInjection inj) : base(inj) { }
public IdentityDomain(ServiceInjection inj) : base(inj) { }
public IdentityService(ServiceInjection inj) : base(inj) { }
public EventDomain(ServiceInjection inj) : base(inj) { }
public DeviceConfigService(ServiceInjection inj) : base(inj) { }