Example #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("SO115", new Info {
                    Title = "SO115", Version = "v1.0"
                });
            });

            ///<summary>
            ///Registrazione dei servizi AutoMapper
            /// </summary>
            services.AddAutoMapper(typeof(Startup));
            var config = new MapperConfigure().Configure();

            services.AddSingleton <IMapper>(sp => config.CreateMapper());

            ///<summary>
            ///Registrazione dei servizi Cors
            /// </summary>
            services.AddCors(options =>
            {
                options.AddPolicy("CorsSo115",
                                  builder =>
                {
                    builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(option =>
            {
                option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
            services.AddSignalR();
            IntegrateSimpleInjector(services);
        }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IConfiguration>(Configuration);

            // Add framework services.
            services
            .AddMvc(config =>
            {   //vyzadani globalni autorizace na vsech strankach, ktere nemaji atribut [AllowAnonymous]
                var defaultPolicy = new AuthorizationPolicyBuilder(new[] { JwtBearerDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme })
                                    .RequireAuthenticatedUser()
                                    .Build();

                config.Filters.Add(new AuthorizeFilter(defaultPolicy));
                //config.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            })
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSession();

            services.AddAutoMapper(cfg => MapperConfigure.Configure(cfg));

            services
            .AddDbContext <ApplicationDbContext>(options => options
                                                 .UseLazyLoadingProxies()
                                                 .UseSqlServer(
                                                     Configuration.GetConnectionString("DefaultConnection"), x => x.MigrationsAssembly("NC_Monitoring.Data")));
            //Configuration.GetConnectionString("DefaultConnection")));

            //services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.Stores.MaxLengthForKeys = 128)
            services
            .AddIdentity <ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            // .AddDefaultUI()//vytvoreni stranek pro prihlaseni /Ideneity/Account/Login atd.
            .AddDefaultTokenProviders()
            .AddUserManager <ApplicationUserManager>()
            .AddRoleManager <ApplicationRoleManager>()
            .AddSignInManager <ApplicationSignInManager>()
            .AddRoles <ApplicationRole>();

            services
            .Configure <IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 2;

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

                // User settings.
                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });

            var key = Encoding.ASCII.GetBytes(SECRET);

            services
            //.AddAuthorization(config =>
            //{
            //    var defaultPolicy = new AuthorizationPolicyBuilder(new[] { JwtBearerDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme })
            //          .RequireAuthenticatedUser()
            //          .Build();

            //    //config.Filters.Add(new AuthorizeFilter(defaultPolicy));
            //    config.DefaultPolicy = defaultPolicy;
            //})
            .ConfigureApplicationCookie(options =>
            {
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = async ctx =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api"))
                        {
                            if (ctx.Response.StatusCode == (int)HttpStatusCode.OK)
                            {
                                ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            }
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        //await Task.FromResult(0);
                    }
                };
            })
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            })
            //    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            //    {
            //        options.Cookie.HttpOnly = true;
            //        options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

            //        options.LoginPath = "/Account/Login";
            //        options.AccessDeniedPath = "/Account/AccessDenied";
            //        options.SlidingExpiration = true;
            //    })
            .AddJwtBearer(cfg =>
            {
                cfg.SaveToken                 = true;
                cfg.RequireHttpsMetadata      = false;    // https off
                cfg.RequireHttpsMetadata      = false;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    //ValidateIssuerSigningKey = true,
                    //IssuerSigningKey = new SymmetricSecurityKey(key),
                    //ValidateIssuer = false,
                    //ValidateAudience = false

                    RequireExpirationTime = true,
                    ValidateIssuer        = true,
                    ValidateAudience      = true,
                    ValidIssuer           = JWTAudience,
                    ValidAudience         = JWTIssuer,
                    IssuerSigningKey      = new SymmetricSecurityKey(key),

                    //ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    //ClockSkew = TimeSpan.Zero
                };
            })
            ;


            services
            .AddTransient <IMonitorRepository, MonitorRepository>()
            .AddTransient <IMonitorManager, MonitorManager>()

            .AddTransient <IRecordRepository, RecordRepository>()

            .AddTransient <IChannelManager, ChannelManager>()
            .AddTransient <IChannelRepository, ChannelRepository>()

            .AddTransient <IScenarioRepository, ScenarioRepository>();

            services
            .AddTransient <IEmailNotificator, EmailNotificator>()
            .AddScoped <SmtpClient>(conf =>
            {
                return(new SmtpClient()
                {
                    Host = Configuration.GetValue <string>("Email:Smtp:Host"),
                    Port = Configuration.GetValue <int>("Email:Smtp:Port"),
                    Credentials = new NetworkCredential(
                        Configuration.GetValue <string>("Email:Smtp:Username"),
                        Configuration.GetValue <string>("Email:Smtp:Password")
                        )
                });
            });
        }
Example #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
            .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
            services.AddCors();
            services.AddDataProtection();
            services.AddHealthChecks();
            services.AddHttpContextAccessor();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            services.AddIdentityClient(options =>
            {
                options.ServiceUrl = options.ServiceUrl = Configuration.GetSection("Services")["IdentityServiceUrl"];
            });

            services.Configure <MailerOptions>(options => Configuration.Bind("MailServiceOptions", options));

            services.AddSwaggerGen(options =>
            {
                options.SwaggerGeneratorOptions.IgnoreObsoleteActions = true;

                options.SwaggerDoc("v1", new Info
                {
                    Title       = "Xyzies.Notification",
                    Version     = $"v1.0.0",
                    Description = ""
                });

                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    In          = "header",
                    Name        = "Authorization",
                    Description = "Please enter JWT with Bearer into field",
                    Type        = "apiKey"
                });

                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", Enumerable.Empty <string>() }
                });

                options.CustomSchemaIds(x => x.FullName);
                options.EnableAnnotations();
                options.DescribeAllEnumsAsStrings();
                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory,
                                                        string.Concat(Assembly.GetExecutingAssembly().GetName().Name, ".xml")));
            });

            services.AddDbContext <NotificationContext>(ctxOptions =>
                                                        ctxOptions.UseSqlServer(Configuration.GetConnectionString("db")));

            #region DI settings

            services.AddScoped <ILogRepository, LogRepository>();
            services.AddScoped <IMessageTemplateRepository, MessageTemplateRepository>();
            services.AddScoped <IMailerService, MailerService>();
            #endregion

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Ignore
            };

            services.AddTcpStreamLogging(options => Configuration.Bind("Logstash", options));

            TypeAdapterConfig.GlobalSettings.Default.PreserveReference(true);
            MapperConfigure.Configure();
        }
Example #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ///<summary>
            ///Registrazione dei servizi Cors
            /// </summary>
            ///
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()
                    .WithOrigins(Configuration.GetSection("AllowedOriginLocal").Value,
                                 Configuration.GetSection("AllowedOriginTest").Value,
                                 Configuration.GetSection("AllowedOriginProd").Value,
                                 Configuration.GetSection("AllowedOriginMatrix").Value)
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .WithExposedHeaders("codicesede", "hubconnectionid", "idUtente", "localip", "DNT", "user-agent", "x-requested-with",
                                        "If-Modified-Since", "Cache-Control", "content-type", "range", "accept", "authorization", "origin");
                });
            });

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "test");
            services.AddSingleton(httpClient);
            services.AddControllers();

            services.AddControllersWithViews();
            services.AddHttpContextAccessor();

            services.AddMemoryCache();
            services.AddMvcCore().AddApiExplorer().AddNewtonsoftJson();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("SO115", new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title = "SO115", Version = "v1.0"
                });
            });

            ///<summary>
            ///Registrazione dei servizi AutoMapper
            /// </summary>
            services.AddAutoMapper(typeof(Startup));
            var config = new MapperConfigure().Configure();

            services.AddSingleton <IMapper>(sp => config.CreateMapper());

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(option =>
            {
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
            services.AddSignalR().AddHubOptions <NotificationHub>(options =>
            {
                options.EnableDetailedErrors = true;
            });
            IntegrateSimpleInjector(services);
        }
Example #5
0
        public static IMapper CreateMapper()
        {
            var config = new MapperConfiguration(cfg => MapperConfigure.Configure(cfg));

            return(config.CreateMapper());
        }
Example #6
0
        } = "/api/device-management-api";                                                       // Default.

        // This method gets called by the runtime. Use this method to add services to the container.
        public virtual void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
            .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
            services.AddCors();
            services.AddDataProtection();
            services.AddHealthChecks();
            services.AddHttpContextAccessor();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.Configure <AssemblyOptions>(options => Configuration.Bind("AssemblyVersion", options));

            services.Configure <ServiceOption>(option => Configuration.Bind("Services", option));

            services.Configure <NotificationSenderExtentionOptions>(options => Configuration.Bind("NotificationHelper", options));

            services.AddIdentityClient(options =>
            {
                options.ServiceUrl = options.ServiceUrl = Configuration.GetSection("Services")["IdentityServiceUrl"];
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerGeneratorOptions.IgnoreObsoleteActions = true;

                options.SwaggerDoc("v1", new Info
                {
                    Title       = "Xyzies.Devices",
                    Version     = $"v1.0.0",
                    Description = ""
                });

                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    In          = "header",
                    Name        = "Authorization",
                    Description = "Please enter JWT with Bearer into field",
                    Type        = "apiKey"
                });

                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", Enumerable.Empty <string>() }
                });

                options.CustomSchemaIds(x => x.FullName);
                options.EnableAnnotations();
                options.DescribeAllEnumsAsStrings();
                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory,
                                                        string.Concat(Assembly.GetExecutingAssembly().GetName().Name, ".xml")));
            });

            services.AddDbContext <DeviceContext>(ctxOptions =>
                                                  ctxOptions.UseSqlServer(Configuration.GetConnectionString("db")));

            services.AddSignalR(hubOptions =>
            {
                hubOptions.EnableDetailedErrors = true;
            }).AddStackExchangeRedis(Configuration.GetConnectionString("redis"), options =>
            {
                options.Configuration.ChannelPrefix = "SignalRDeviceManagment";
            });

            services.AddMemoryCache();

            #region DI settings

            services.AddScoped <IHttpService, HttpService>();
            services.AddScoped <IDeviceRepository, DeviceRepository>();
            services.AddScoped <IDeviceService, DeviceService>();
            services.AddScoped <IValidationHelper, ValidationHelper>();
            services.AddScoped <IDeviceHistoryRepository, DeviceHistoryRepository>();
            services.AddScoped <ICommentRepository, CommentRepository>();
            services.AddScoped <ICommentService, CommentService>();
            services.AddScoped <IDeviceHistoryService, DeviceHistoryService>();
            services.AddScoped <ILogRepository, LogRepository>();
            services.AddScoped <INotificationSender, NotificationSender>();

            RedisConnection.InitializeConnectionString(Configuration.GetSection("ConnectionStrings")["redis"]);
            services.AddSingleton <RedisStore>();

            services.AddHostedService <QueuedHostedService>();
            services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>();
            services.AddSingleton <BadDisconnectSocketService>();

            #endregion

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Ignore
            };

            _logger.LogInformation($"[Startup.ConfigureServices] dispute environment: {_deviceEnvironment}");
            if (_deviceEnvironment?.ToLower() != _deviceTestEnvironment.ToLower())
            {
                services.AddTcpStreamLogging(options => Configuration.Bind("Logstash", options));
            }
            TypeAdapterConfig.GlobalSettings.Default.PreserveReference(true);
            MapperConfigure.Configure();
        }