// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { const string signingSecurityKey = "0d5b3235a8b403c3dab9c3f4f65c07fcalskd234n1k41230"; var signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); services.AddControllers(); const string jwtSchemeName = "JwtBearer"; var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = "DemoApp", ValidateAudience = true, ValidAudience = "DemoAppClient", ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; }); }
public void ConfigureServices(IServiceCollection services) { const string signingSecurityKey = "0d5b3235a8b403c3dab9c3f4f65c07fcalskd234n1k41230"; var signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); const string jwtSchemeName = "JwtBearer"; var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = "MyShop", ValidateAudience = true, ValidAudience = "MyShopClient", ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; }); services.AddDbContext <DatabaseContext>(o => o.UseNpgsql("Host=localhost;Port=5434;Database=postgres")); services.AddDefaultIdentity <CustomUserIdentity>().AddEntityFrameworkStores <DatabaseContext>(); services.AddControllers(); }
public UsersControllerTests() { db = new RecipeBookContext(); signingSymmetricKey = new SigningSymmetricKey("zigmuntkyzaneusedelka228"); controller = new UsersController(db, signingSymmetricKey); }
public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure <JwtOptions>(Configuration); services.AddDbContext <MaelstormRepository, MaelstormContext>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IAccountService, AccountService>(); services.AddScoped <IPasswordService, PasswordService>(); services.AddScoped <IEmailService, EmailService>(); services.AddScoped <IDialogService, DialogService>(); services.AddScoped <ISQLService, SQLService>(); services.AddScoped <IFinderService, FinderService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <ISessionService, SessionService>(); services.AddScoped <ISignalRSessionService, SignalRSessionService>(); #region Jwt / session validation services.Configure <JwtOptions>(Configuration.GetSection("Jwt")); string signingSecurityKey = Configuration["Jwt:SigningKey"]; var signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <ISigningKeys>(signingKey); string encodingSecurityKey = Configuration["Jwt:EncryptingKey"]; var encryptionEncodingKey = new EncryptingSymmetricKey(encodingSecurityKey); services.AddSingleton <IEncryptingKeys>(encryptionEncodingKey); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // раскоментить при ошибках с jwt и всякого рода шифрования, чтобы видеть инфу об ошибке //IdentityModelEventSource.ShowPII = true; const string jwtSchemeName = "JwtBearer"; IJwtSigningDecodingKey signingDecodingKey = (IJwtSigningDecodingKey)signingKey; IJwtEncryptingDecodingKey encryptingDecodingKey = (IJwtEncryptingDecodingKey)encryptionEncodingKey; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), TokenDecryptionKey = encryptingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidateAudience = true, ValidAudience = Configuration["Jwt:Audience"], ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(Int32.Parse(Configuration["Jwt:ClockSkew"])) }; jwtBearerOptions.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); }, OnTokenValidated = async context => { var sessionService = context.HttpContext.RequestServices.GetService <ISessionService>(); if (await sessionService.IsSessionClosed(context.Principal.FindFirst("SessionId")?.Value) || context.Principal.FindFirst("Ip")?.Value != context.HttpContext.Connection.RemoteIpAddress.ToString()) { context.Fail("Invalid session"); } } }; }); #endregion services.AddDistributedRedisCache(option => { option.Configuration = Configuration["Redis:Address"]; option.InstanceName = "maelstorm"; }); services.AddSignalR(); }
// 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_1); #region Authorization and Autontification configuring... var signingKey = new SigningSymmetricKey(Configuration.GetValue <string>("JWTOptions:SecretKey")); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services .AddMemoryCache() .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; //options.Events = new JwtBearerEvents //{ // OnMessageReceived = context => // { // var accessToken = context.Request.Query["access_token"]; // // If the request is for our hub... // var path = context.HttpContext.Request.Path; // if (!string.IsNullOrEmpty(accessToken)) // { // // Read the token out of the query string // context.Token = accessToken; // } // return Task.CompletedTask; // } //}; }); #endregion #region Configure our services... services.AddTransient <IUoW, UnitOfWork>(); services.AddTransient <IAuthService, AuthService>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IRoleService, RoleService>(); services.AddTransient <IPhotoService, PhotoService>(); services.AddTransient <IEmailService, EmailService>(); services.AddTransient <IMapService, MapService>(); services.AddTransient <ITankService, TankService>(); services.AddSingleton <ICacheHelper, CacheHelper>(); services.AddMediatR(typeof(RegisterVerificationHandler).Assembly); services.Configure <EmailOptionsModel>(Configuration.GetSection("EmailSenderOptions")); //services.Configure<ImageOptionsModel>(Configuration.GetSection("ImageWidths")); #endregion services.AddCors(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "BattleTanks API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below. \r\n\r\nExample: 'Bearer 12345abcdef'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List <string>() } }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddAutoMapper(typeof(AutoMapperProfile).GetTypeInfo().Assembly); services.AddDbContext <AppDbContext>(options => options.UseSqlServer(Configuration .GetConnectionString("DefaultConnection"))); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddMvc().AddFluentValidation(fv => { fv.RunDefaultMvcValidationAfterFluentValidationExecutes = true; }); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new UserMapping()); mc.AddProfile(new CategoryMapping()); mc.AddProfile(new ArticleMapping()); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); services.AddTransient <IUserService, UserService>(); services.AddTransient <ICategoryService, CategoryService>(); services.AddTransient <ICategoriesContext, CategoriesContext>(); services.AddTransient <IUsersContext, UsersContext>(); services.AddTransient <IArticleService, ArticleService>(); services.AddTransient <IArticleContext, ArticleContext>(); services.AddTransient <IValidator <CreateUserRequest>, CreateUserRequestValidator>(); services.AddTransient <IArticleRepository, ArticleRepository>(); services.AddTransient <ICategoryRepository, CategoryRepository>(); services.AddTransient <IUserRepository, UserRepository>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); services.Configure <Settings>(options => { options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value; options.Database = Configuration.GetSection("MongoConnection:Database").Value; }); const string signingSecurityKey = "0d5b3235a8b403c3dab9c3f4f65c07fcalskd234n1k41230"; var signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); const string jwtSchemeName = "JwtBearer"; var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = "DemoApp", ValidateAudience = true, ValidAudience = "DemoAppClient", ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(3600) }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // The following line enables Application Insights telemetry collection. services.AddApplicationInsightsTelemetry(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddScoped <IDataService <AssignmentViewModel>, AssignmentsService>(); services.AddScoped <IDataService <ProjectViewModel>, ProjectsService>(); services.AddScoped <ITableClient, AzureTableClient>(); var settings = AppSettings.LoadAppSettings(); var signingSecurityKey = settings.SigningSecurityKey; var signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); const string jwtSchemeName = "JwtBearer"; var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = "AiratApp", ValidateAudience = true, ValidAudience = "AiratClients", ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; }); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Assignments", Version = "v1" }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.AddSecurityDefinition("oauth2", new ApiKeyScheme { Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"", In = "header", Name = "Authorization", Type = "apiKey" }); c.OperationFilter <SecurityRequirementsOperationFilter>(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region Cors policy services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() ); }); #endregion #region Binding services.AddScoped <IMongoManager, MongoManager>(); services.AddScoped <IFileService, FileService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <INotifier, ConcreteEmailNotifier>(); services.AddSingleton <IHasher, Hasher>(); services.AddScoped <IRedisRepo, RedisRepo>(); services.AddScoped <IAuthService, AuthService>(); #endregion services.AddControllers() .AddFluentValidation(fv => { fv.RegisterValidatorsFromAssemblyContaining <UserValidator>(); fv.RegisterValidatorsFromAssemblyContaining <AuthValidator>(); fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false; }); #region MongoSettings services.Configure <MongoSettings>(options => { options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value; options.Database = Configuration.GetSection("MongoConnection:Database").Value; }); services.AddScoped <IMongoDatabase>(provider => { var settings = provider.GetService <IOptions <MongoSettings> >(); var client = new MongoClient(settings.Value.ConnectionString); var db = client.GetDatabase(settings.Value.Database); return(db); }); #endregion #region AutoMapper MapperConfiguration mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mapperConfig.CreateMapper(); services.AddSingleton(mapper); #endregion #region Action model state filter services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { var modelStateError = actionContext.ModelState.FirstOrDefault(m => m.Value.ValidationState == ModelValidationState.Invalid); KeyValuePair <string, string> error; error = (modelStateError.Equals(default(KeyValuePair <string, ModelStateEntry>))) ? new KeyValuePair <string, string>() : new KeyValuePair <string, string>( modelStateError.Key, modelStateError.Value.Errors.First().ErrorMessage ?? "the input was not valid" ); return(new BadRequestObjectResult(error)); }; }); #endregion #region MailKit services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings")); #endregion #region Redis services.Configure <RedisSettings>(options => { options.Host = Configuration.GetSection("RedisConnection:Host").Value; options.Port = Configuration.GetSection("RedisConnection:Port").Value; }); services.AddScoped <IConnectionMultiplexer>(provider => { var settings = provider.GetService <IOptions <RedisSettings> >(); IConnectionMultiplexer redisCient = ConnectionMultiplexer.Connect($"{settings.Value.Host}:{settings.Value.Port}"); return(redisCient); }); #endregion #region JWT string signingSecurityKey = Configuration["JWTSettings:Secret"]; SigningSymmetricKey signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); IJwtSigningDecodingKey signingDecodingKey = signingKey; string encodingSecurityKey = Configuration["JWTSettings:EncodingKey"]; EncryptingSymmetricKey encryptionEncodingKey = new EncryptingSymmetricKey(encodingSecurityKey); services.AddSingleton <IJwtEncryptingEncodingKey>(encryptionEncodingKey); IJwtEncryptingDecodingKey encryptingDecodingKey = encryptionEncodingKey; string jwtSchemeName = Configuration["JWTSettings:SchemaName"].ToString(); services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), TokenDecryptionKey = encryptingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = "DjelatoApp", ValidateAudience = true, ValidAudience = "DjelatoAppClient", ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(10) }; }); #endregion }
private void AddServices(IServiceCollection services) { /* Подключение базы данных */ // добавляем контекст UsersContext в качестве сервиса в приложение services.AddDbContext <DataBaseContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), sqlServerOptionsAction: sqlOptions => { sqlOptions.EnableRetryOnFailure( maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }); services.AddTransient <IUsersDataBase, UsersDataBase>(); services.AddTransient <IRolesDataBase, RolesDataBase>(); /* Добавление листа запросов на синхронизацию */ ListRequests SyncRequestsList = new ListRequests(); services.AddSingleton(SyncRequestsList); // фоновая очистка списка запросов на синхронизацию services.AddHostedService <ClearingRequests>(); /* Настройка jWT (токенов) */ //string signingSecurityKey = Convert.ToString(Salt.Create()); var signingKey = new SigningSymmetricKey(AuthOptions.KEY); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; const string jwtSchemeName = "JwtBearer"; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { // настройка записи токена в строку запроса (для работы с сокетами) jwtBearerOptions.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; // если запрос направлен хабу var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/protocoldh"))) { // получаем токен из строки запроса context.Token = accessToken; } return(Task.CompletedTask); } }; // настройка параметров токена jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <RequestLocalizationOptions>(options => { var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("ru") }; options.DefaultRequestCulture = new RequestCulture("ru"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); services.AddDbContext <ApplicationDbContext>(options => options.UseNpgsql( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity <ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles <IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>(); var signingKey = new SigningSymmetricKey(AuthOptions.KEY); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); // services.AddIdentityServer() // services.AddAuthentication() // .AddIdentityServerJwt(); var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "JwtBearer"; options.DefaultChallengeScheme = "JwtBearer"; }) .AddJwtBearer("JwtBearer", jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; }); services.AddControllersWithViews(); services.AddRazorPages(); services.AddMvc().AddNewtonsoftJson(options => { options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region Authorization and Autontification configuring... var signingKey = new SigningSymmetricKey(Configuration.GetValue <string>("JWTOptions:SecretKey")); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services .AddMemoryCache() .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; // If the request is for our hub... var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chatRoom"))) { // Read the token out of the query string context.Token = accessToken; } return(Task.CompletedTask); } }; }); #endregion services.AddDbContext <AppDbContext>(options => options.UseSqlServer(Configuration .GetConnectionString("AzureConnection"))); #region Configure our services... services.AddTransient <IUnitOfWork, UnitOfWork>(); services.AddTransient <IAuthService, AuthService>(); services.AddTransient <IEventService, EventService>(); services.AddTransient <IMessageService, MessageService>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IRoleService, RoleService>(); services.AddTransient <ICountryService, CountryService>(); services.AddTransient <ICityService, CityService>(); services.AddTransient <ICategoryService, CategoryService>(); services.AddTransient <ICommentService, CommentService>(); services.AddSingleton <ICacheHelper, CacheHelper>(); services.AddTransient <IPhotoService, PhotoService> (); services.Configure <ImageOptionsModel>(Configuration.GetSection("ImageWidths")); services.AddTransient <IEmailService, EmailService>(); services.Configure <EmailOptionsModel>(Configuration.GetSection("EmailSenderOptions")); #endregion services.AddCors(); services.AddMvc().AddFluentValidation() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddTransient <IValidator <LoginDto>, LoginDtoValidator>(); services.AddTransient <IValidator <ChangePasswordDto>, ChangePasswordDtoValidator>(); services.AddTransient <IValidator <CategoryDto>, CategoryDtoValidator>(); services.AddTransient <IValidator <CommentDto>, CommentDtoValidator>(); services.AddTransient <IValidator <DTO.EventDto>, EventDtoValidator>(); services.AddTransient <IValidator <AttitudeDto>, AttitudeDtoValidator>(); services.AddTransient <IValidator <RateDto>, RateDtoValidator>(); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); services.AddMediatR(typeof(EventCreatedHandler).Assembly); services.AddAutoMapper(typeof(AutoMapperProfile).GetTypeInfo().Assembly); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "EventsExpress API", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddSignalR(); services.AddSingleton <IUserIdProvider, SignalRUserIdProvider>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //----Secret key generation----- string signingSecurityKey = Configuration.GetSection("JwtConfig").GetSection("ServiceApiKey").Value; var signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); //------------------------------ // инъекция соeдинение NORTHWNDContext - контекст базы данных на SQL Servere string connection = Configuration.GetConnectionString("OMSDatabase"); services.AddDbContext <NorthwindContext>(options => options.UseSqlServer(connection)); //------------------------------- services.AddControllers(); //----JWTBearer---- const string jwtSchemeName = "JwtBearer"; var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = "OMSWebMini", ValidateAudience = true, ValidAudience = "OMSWebMiniClient", ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; }); //---------------- //string connection = Configuration.GetConnectionString("OMSDatabase"); //services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(connection)); services.AddSwaggerDocument(config => { config.PostProcess = document => { document.Info.Version = "v1"; document.Info.Title = "OMSServiceMini"; document.Info.Description = "A simple study project ASP.NET Core web API"; document.Info.Contact = new NSwag.OpenApiContact { Name = "Boris Minin", Email = "*****@*****.**", Url = "https://www.facebook.com/borisminindeveloper" }; document.Info.License = new NSwag.OpenApiLicense { Name = "Look at my GitHub", Url = "https://github.com/BorisMinin" }; }; }); // https://stackoverflow.com/questions/59199593/net-core-3-0-possible-object-cycle-was-detected-which-is-not-supported services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); }
public void ConfigureServices(IServiceCollection services) { IConfigurationSection securitySection = Configuration.GetSection("Security"); var signingKey = new SigningSymmetricKey(securitySection["Key"]); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); services.AddSingleton <IUserIdProvider, CustomUserIdProvider>(); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext <ApplicationContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity <IdentityUser>(options => { options.SignIn.RequireConfirmedAccount = false; options.Password.RequiredLength = 1; options.Password.RequireNonAlphanumeric = false; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequireDigit = false; }) .AddEntityFrameworkStores <ApplicationDbContext>(); services.AddTransient <EmailService>(); services.AddControllersWithViews(); services.AddRazorPages(); services.AddSignalR().AddHubOptions <ChatHub>(options => { options.EnableDetailedErrors = true; }); services.AddMvc(); var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services.AddAuthentication() .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }) .AddGoogle(options => { IConfigurationSection googleAuthNSection = Configuration.GetSection("Authentication:Google"); options.ClientId = googleAuthNSection["ClientId"]; options.ClientSecret = googleAuthNSection["ClientSecret"]; options.SaveTokens = true; }) .AddCookie(options => { options.LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Login"); }); }
public void ConfigureServices(IServiceCollection services) { var connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <Context>(options => options.UseMySql(connection, m => m.MigrationsAssembly("ToDoList.DAL"))); services.AddScoped(typeof(IRepository <>), typeof(Repository <>));// Problems with singleton parents // There is only one helper so we use so, in either case we have an option to use Autofac services.AddSingleton <IAccountHelper, AccountHelper>(); services.AddSingleton <IWebsocketHandler, WebsocketHandler>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies() .Where(a => a?.FullName != null && a.FullName.StartsWith("ToDoList.API"))); services.AddRouting(); services.AddCors(options => { options.AddPolicy(_corsDevPolicy, builder => builder.WithOrigins("https://localhost:44336", "https://localhost:44336") .AllowAnyHeader() .AllowCredentials() .WithExposedHeaders("Token-Expired", "WWW-Authenticate", "Authorization") .AllowAnyMethod()); }); services.AddControllers() .AddControllersAsServices() .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); // Jwt with signing key and encoding, it's have 5(there is no second because of symmetric) segments in itself(strongly private, ps i think so) const string signingSecurityKey = JwtSettings.SigningKey; var signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); const string encodingSecurityKey = JwtSettings.EncodingKey; var encryptionEncodingKey = new EncryptingSymmetricKey(encodingSecurityKey); services.AddSingleton <IJwtEncryptingEncodingKey>(encryptionEncodingKey); var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; var encryptingDecodingKey = (IJwtEncryptingDecodingKey)encryptionEncodingKey; services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = true; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = JwtSettings.ValidateIssuer, ValidIssuer = JwtSettings.ValidIssuer, ValidateAudience = JwtSettings.ValidateAudience, ValidAudience = JwtSettings.ValidAudience, ValidateLifetime = JwtSettings.ValidateLifetime, IssuerSigningKey = signingDecodingKey.GetKey(), TokenDecryptionKey = encryptingDecodingKey.GetKey(), ValidateIssuerSigningKey = JwtSettings.ValidateIssuerSigningKey, RequireExpirationTime = JwtSettings.RequireExpirationTime, ClockSkew = JwtSettings.ClockSew }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); } }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Required for HttpClient support in the Blazor Client project services.AddHttpClient(); services.AddScoped <HttpClient>(); // Pass settings to other components services.AddSingleton <IConfiguration>(Configuration); services.AddTransient <IUnitOfWork, UnitOfWork>(provider => new UnitOfWork(Configuration["ConnectionString"])); //current user всегда scoped!! //services.AddScoped<ServiceCurrentUser>(); services.AddScoped <IServiceAuthentication, ServiceAuthentication>(); services.AddScoped <ServiceScheduler>(); services.AddScoped <ServiceCommon>(); //services.AddScoped<ServiceStudentOffice_DisciplineSelect>(); //services.AddScoped<ServicePulse>(); //services.AddScoped<ServiceTests>(); FluentMapper.Initialize(config => { config.AddMap(new MapKadr()); config.AddMap(new MapMoving()); config.AddMap(new MapGroup()); config.AddMap(new MapPosada()); config.AddMap(new MapKafedra()); config.AddMap(new MapEducPlanSpec()); config.AddMap(new MapDisciplineSelected()); config.AddMap(new MapLogOnd()); config.AddMap(new MapTelegramBotHistory()); config.AddMap(new MapTest_Shablon()); config.AddMap(new MapTest_ShablonDetail()); config.AddMap(new MapTest_StartedTestQuestion()); config.AddMap(new MapTest_StartedTestAnswer()); config.AddMap(new MapZnoExam()); config.AddMap(new MapZnoSpec()); }); //*** JWT string signingSecurityKey = Configuration.GetSection("PdaaToken:signingSecurityKey").Value; // "PDAA_2020-06-01_0d5b3235a8b403c3dab9c3f4f65c07fcalskd234n1k41230"; var signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); //*** JWT services.AddControllers(); //*** JWT const string jwtSchemeName = "JwtBearer"; var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = Configuration.GetSection("PdaaToken:issuer").Value, //"pdaa.asu.api", ValidateAudience = true, ValidAudience = Configuration.GetSection("PdaaToken:audience").Value, //"pdaa.asu.client", ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; }); //*** JWT }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton <ILoggerManager, LoggerManager>(); services.AddCors(); // Add framework services. services.AddMvc(); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy")); }); #region JWT Authentication const string signingSecurityKey = AuthorizationDataModel.SigningSecurityKey; var signingKey = new SigningSymmetricKey(signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); const string jwtSchemeName = AuthorizationDataModel.JwtSchemeName; var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = AuthorizationDataModel.ValidIssuer, ValidateAudience = true, ValidAudience = AuthorizationDataModel.ValidAudience, ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = tokenValidationParameters; }); #endregion #region DI services.AddTransient <IDbContext>(s => new DbContext(Configuration.GetConnectionString("DefaultConnection"))); services.AddTransient <IPasswordHash, PasswordHash>(); services.AddTransient <ISessionTokenGenerate, SessionTokenGenerate>(); services.AddTransient <IRegistrationService, RegistrationService>(); services.AddTransient <IAuthorizationService, AuthorizationService>(); services.AddTransient <IProductCategoryService, ProductCategoryService>(); services.AddTransient <IProductInformationService, ProductInformationService>(); services.AddTransient <IProductService, ProductService>(); services.AddTransient <IUserOrderService, UserOrderService>(); services.AddTransient <IUserSystemService, UserSystemService>(); #endregion services.AddMvcCore(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); #region CORS services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory(CorsPolicy)); }); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.WithOrigins("http://localhost:4200"); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy(CorsPolicy, corsBuilder.Build()); }); #endregion }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var signingKey = new SigningSymmetricKey(_signingSecurityKey); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); var encryptionEncodingKey = new EncryptingSymmetricKey(_encodingSecurityKey); services.AddSingleton <IJwtEncryptingEncodingKey>(encryptionEncodingKey); //The connection string to database must be in the secrets.json file. services.AddDbContext <ApplicationContext>(options => options.UseSqlServer(_connectionString)); services.AddDbContext <AdventureWorks2017Context>(options => options.UseSqlServer(_adventureWorks2017ConnectionString)); // Auto Mapper Configurations var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddApiVersioning(o => { o.ApiVersionReader = new HeaderApiVersionReader("api-version"); o.AssumeDefaultVersionWhenUnspecified = true; o.DefaultApiVersion = new ApiVersion(1, 0); o.ReportApiVersions = true; }); services.AddSwaggerDocument(); const string jwtSchemeName = "JwtBearer"; var signingDecodingKey = (IJwtSigningDecodingKey)signingKey; var encryptingDecodingKey = (IJwtEncryptingDecodingKey)encryptionEncodingKey; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = jwtSchemeName; options.DefaultChallengeScheme = jwtSchemeName; }) .AddJwtBearer(jwtSchemeName, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), TokenDecryptionKey = encryptingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = "SampleOfWebAPI", ValidateAudience = true, ValidAudience = "WebAPI", ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(1) }; }); services.AddScoped <IRepository <Comment>, Repository <Comment> >(); services.AddScoped <ICommentService, CommentService>(); services.AddScoped <IRepository <Post>, Repository <Post> >(); services.AddScoped <IPostService, PostService>(); }