private void AddJwtServices(IServiceCollection services) { var signingKey = new SigningSymmetricKey(Configuration["SigningSecurityKey"]); services.AddSingleton <IJwtSigningEncodingKey>(signingKey); var encryptionEncodingKey = new EncryptingSymmetricKey(Configuration["EncodingSecurityKey"]); services.AddSingleton <IJwtEncryptingEncodingKey>(encryptionEncodingKey); IJwtSigningDecodingKey signingDecodingKey = signingKey; IJwtEncryptingDecodingKey encryptingDecodingKey = encryptionEncodingKey; services .AddAuthentication(options => { options.DefaultAuthenticateScheme = Configuration["JwtSchemeName"]; options.DefaultChallengeScheme = Configuration["JwtSchemeName"]; }) .AddJwtBearer(Configuration["JwtSchemeName"], jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingDecodingKey.GetKey(), TokenDecryptionKey = encryptingDecodingKey.GetKey(), ValidateIssuer = true, ValidIssuer = Configuration["JwtIssuer"], ValidateAudience = true, ValidAudience = Configuration["JwtAudience"], ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(5) }; }); }
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) { #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 }