Пример #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext <ApplicationContext>(options => options.UseMySql(mySqlConnectionStr,
                                                                                   mySqlOption =>
                                                                                   mySqlOption.ServerVersion("10.1.5-MariaDb")));
            var signingKey = new SigningSymmetricKey(AuthOptions.SIGNING_SECURITY_KEY);

            services.AddSingleton <IKdPwSigningEncodingKey>(signingKey);

            var encryptionEncodingKey = new EncryptingSymmetricKey(AuthOptions.ENCODING_SECURITY_KEY);

            services.AddSingleton <IKdPwEncryptingEncodingKey>(encryptionEncodingKey);

            var signingDecodingKey    = (IKdPwSigningDecodingKey)signingKey;
            var encryptingDecodingKey = (IKdPwEncryptingDecodingKey)encryptionEncodingKey;

            services
            .AddAuthentication(options => {
                options.DefaultAuthenticateScheme = AuthOptions.SCHEME;
                options.DefaultChallengeScheme    = AuthOptions.SCHEME;
            })
            .AddJwtBearer(AuthOptions.SCHEME, jwtBearerOptions => {
                jwtBearerOptions.RequireHttpsMetadata      = false;
                jwtBearerOptions.SaveToken                 = true;
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = signingDecodingKey.GetKey(),
                    TokenDecryptionKey       = encryptingDecodingKey.GetKey(),

                    ValidateIssuer = false,
                    //ValidIssuer = AuthOptions.ISSUER,

                    ValidateAudience = false,
                    //ValidAudience = AuthOptions.AUDIENCE,

                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.FromSeconds(5)
                };
            });
            services.AddScoped <IPublicService, PublicService>();
            services.AddScoped <IProtectedService, ProtectedService>();
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            services.AddMvc();
            services.AddControllers();
            services.AddCors();
        }
Пример #2
0
        public AccountHelperTests()
        {
            _accountHelper = new AccountHelper();

            // Setting up a jwe keys
            const string signingSecurityKey = "745hvv43uhvfnvu2v";
            var          signingKey         = new SigningSymmetricKey(signingSecurityKey);

            const string encodingSecurityKey   = "dfkng20jfsdjfvsdmvw";
            var          encryptionEncodingKey = new EncryptingSymmetricKey(encodingSecurityKey);

            _signingEncodingKey    = signingKey;
            _encryptingEncodingKey = encryptionEncodingKey;
        }
Пример #3
0
        // 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);

            const string encodingSecurityKey   = "k72gnxq3pkum9toiub48o8s8sdbjhme1tg0m3p4jfkzovsgdqzgv6t47ig3tr5d9";
            var          encryptionEncodingKey = new EncryptingSymmetricKey(encodingSecurityKey);

            services.AddSingleton <IJwtEncryptingEncodingKey>(encryptionEncodingKey);

            services.AddControllers();

            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    = "DemoApp",

                    ValidateAudience = true,
                    ValidAudience    = "DemoAppClient",

                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.FromSeconds(5)
                };
            });
        }
Пример #4
0
        // 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(Configuration["Jwt:SigningKey"]);

            services.AddSingleton <IJwtSigningEncodingKey>(signingKey);

            var encryptionEncodingKey = new EncryptingSymmetricKey(Configuration["Jwt:EncodingKey"]);

            services.AddSingleton <IJwtEncryptingEncodingKey>(encryptionEncodingKey);

            services.AddTransient <ITokenService, TokenService>();
            services.AddTransient <IPasswordHasher, PasswordHasher>();

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

            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,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidAudience    = Configuration["Jwt:Site"],
                    ValidIssuer      = Configuration["Jwt:Site"],
                    ClockSkew        = TimeSpan.FromMinutes(Convert.ToInt32(Configuration["Jwt:ExpiryInMinutes"]))
                };
            });
        }
Пример #5
0
        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)
                };
            });
        }
Пример #6
0
        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);
                    }
                };
            });
        }
Пример #7
0
        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();
        }
Пример #8
0
        // 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
        }
Пример #9
0
        // 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>();
        }