Exemplo n.º 1
0
        public static IServiceCollection AddIdentityServices(this IServiceCollection services,
                                                             IConfiguration config)
        {
            var builder = services.AddIdentityCore <AppUser>(o => {
                o.Password.RequireDigit           = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 6;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(AppRole), builder.Services);
            builder.AddEntityFrameworkStores <AppIdentityDbContext>();
            builder.AddErrorDescriber <LocalizedIdentityErrorDescriber>();
            builder.AddDefaultTokenProviders();
            builder.AddSignInManager <SignInManager <AppUser> >();
            builder.AddRoleValidator <RoleValidator <AppRole> >();
            builder.AddRoleManager <RoleManager <AppRole> >();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:Key"])),
                    ValidIssuer      = config["Token:Issuer"],
                    ValidateIssuer   = true,
                    ValidateAudience = false
                };
            });

            return(services);
        }
Exemplo n.º 2
0
        public static IServiceCollection RegisterServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext <DatabaseContext>(options =>
                                                    options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

            var builder = services.AddIdentityCore <User>(o =>
            {
                o.Password.RequireDigit           = true;
                o.Password.RequireLowercase       = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 8;
                o.User.RequireUniqueEmail         = true;
            });

            builder = new IdentityBuilder(builder.UserType, builder.Services);
            builder.AddEntityFrameworkStores <DatabaseContext>();
            builder.AddDefaultTokenProviders();

            // Repositories
            services.AddScoped <IExamRepository, ExamRepository>();
            services.AddScoped <ICourseRepository, CourseRepository>();
            services.AddScoped <IClassroomRepository, ClassroomRepository>();
            services.AddScoped <IAppUserManager, AppUserManager>();

            // Services
            services.AddScoped <IExamService, ExamService>();
            services.AddScoped <ICourseService, CourseService>();
            services.AddScoped <IClassroomService, ClassroomService>();
            return(services);
        }
Exemplo n.º 3
0
        public static void ConfigureIdentity(this IServiceCollection services)
        {
            IdentityBuilder builder = services.AddIdentityCore <User>(opts => {
                opts.SignIn.RequireConfirmedEmail    = true;
                opts.Lockout.MaxFailedAccessAttempts = 10;
                opts.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                opts.User.RequireUniqueEmail         = true;
                opts.Lockout.AllowedForNewUsers      = false;
            });

            // .AddUserValidator<UniqueEmail<User>>();

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <DefaultDataContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();
            builder.AddDefaultTokenProviders();

            // services.Configure<IdentityOptions>(options =>
            // {
            //     // Default Lockout settings.
            //     options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(1);
            //     options.Lockout.MaxFailedAccessAttempts = 5;
            //     options.Lockout.AllowedForNewUsers = true;
            //     options.SignIn.RequireConfirmedEmail = true;
            //     options.User.RequireUniqueEmail = true;
            // });

            // Add cokkies to the application the only resason im using this is for lockout attempt
            services.AddAuthentication().AddApplicationCookie();
        }
Exemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("DefaultConnection");

            services.AddEntityFrameworkNpgsql().AddDbContext <DBContext>(options => options.UseNpgsql(connectionString));

            IdentityBuilder builder = services.AddIdentityCore <IdentityUser>(options =>
            {
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = true;
                options.Password.RequireLowercase       = true;
            }
                                                                              );

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddRoleManager <RoleManager <IdentityRole> >();
            builder.AddSignInManager <SignInManager <IdentityUser> >();
            builder.AddEntityFrameworkStores <DBContext>();
            builder.AddDefaultTokenProviders();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignOutScheme      = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration["JwtIssuer"],
                    ValidAudience    = Configuration["JwtIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
                    ClockSkew        = TimeSpan.Zero
                };
            });

            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();// For anyone access.
            corsBuilder.AllowCredentials();


            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", corsBuilder.Build());
            });

            services.AddMvc();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        }
Exemplo n.º 5
0
        /// <summary>
        /// The whole configuration
        /// </summary>
        /// <param name="services"></param>
        public static void Configure(IServiceCollection services, IConfiguration configuration)
        {
            // Add ApplicationContext
            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("SqlConnection")));

            var builder = services.AddIdentityCore <IdentityUser>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 4;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores <ApplicationDbContext>();
            builder.AddRoleValidator <RoleValidator <IdentityRole> >();
            builder.AddRoleManager <RoleManager <IdentityRole> >();
            builder.AddUserManager <UserManager <IdentityUser> >();
            builder.AddSignInManager <SignInManager <IdentityUser> >();
            builder.AddDefaultTokenProviders();
            //builder.add

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Security:Key"])),
                    ValidIssuer      = configuration["Security:Issuer"],
                    ValidAudience    = configuration["Security:Audience"]
                };
            });
        }
Exemplo n.º 6
0
        public IIdentityServerBuilder cofigurIdenttyServer(IServiceCollection services)
        {
            IdentityBuilder builder = services.AddIdentity <IdentityUser, IdentityRole>(option =>
            {
                option.Password.RequireDigit           = false;
                option.Password.RequiredLength         = 4;
                option.Password.RequireUppercase       = false;
                option.Password.RequireNonAlphanumeric = false;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores <DBDataContext>();
            var builderIs4 = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                             .AddAspNetIdentity <IdentityUser>();

            builderIs4.AddDeveloperSigningCredential();
            builder.AddDefaultTokenProviders();
            return(builderIs4);
        }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //        services.AddDbContext<DataContext>(opt =>
            // {
            //     opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            // });

            services.AddDbContext <DataContext>(options =>
                                                options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
            services.AddControllers().AddNewtonsoftJson(options =>
                                                        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                                        );;

            services.AddCors(opt => {
                opt.AddPolicy("CorsPolicy", policy => {
                    policy
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithOrigins("http://localhost:3000");
                });
            });


            services.AddMediatR(typeof(Login.Handler).Assembly);
            services.AddMvc(opt => {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            }).AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining <Login>());


            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt => {
                opt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
            });

            //services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<DataContext>();//.AddDefaultTokenProviders();

            IdentityBuilder builder = services.AddIdentityCore <AppUser>();

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores <DataContext>();
            builder.AddSignInManager <SignInManager <AppUser> >();
            builder.AddRoles <IdentityRole>();
            builder.AddRoleManager <RoleManager <IdentityRole> >();
            builder.AddDefaultTokenProviders();

            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IUserAccessor, UserAccessor>();
        }
Exemplo n.º 8
0
 /// <summary>
 /// 重写以实现 AddIdentity 之后的构建逻辑
 /// </summary>
 /// <param name="builder"></param>
 /// <returns></returns>
 protected override IdentityBuilder AddIdentityBuild(IdentityBuilder builder)
 {
     //如需要昵称唯一,启用下面这个验证码
     //builder.AddUserValidator<UserNickNameValidator<User, Guid>>();
     //builder.AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<User, Role>>();
     //builder.AddDefaultUI();
     return(builder.AddDefaultTokenProviders());
 }
        private static IdentityBuilder AddTokenProviders(this IdentityBuilder identityBuilder)
        {
            identityBuilder
            .AddDefaultTokenProviders()
            .AddTokenProvider <EmailConfirmationTokenProvider <User> >("EmailConfirmation");

            return(identityBuilder);
        }
Exemplo n.º 10
0
 /// <summary>
 /// 重写以实现 AddIdentity 之后的构建逻辑
 /// </summary>
 /// <param name="builder"></param>
 /// <returns></returns>
 protected override IdentityBuilder AddIdentityBuild(IdentityBuilder builder)
 {
     //https:/www.myget.org/F/archertrister/api/v3/index.json
     //如需要昵称唯一,启用下面这个验证码
     //builder.AddUserValidator<UserNickNameValidator<User, int>>();
     builder.AddDefaultUI();
     return(builder.AddDefaultTokenProviders());
 }
Exemplo n.º 11
0
        public static void ConfigureIdentity(this IServiceCollection services)
        {
            IdentityBuilder builder = services
                                      .AddIdentityCore <User>(q => { q.User.RequireUniqueEmail = true; })
                                      .AddRoles <Role>();

            builder.AddEntityFrameworkStores <DatabaseContext>();

            builder.AddDefaultTokenProviders();
        }
Exemplo n.º 12
0
        public static void IdentityConfiguration(this IServiceCollection services)
        {
            //identity config
            var builder         = services.AddIdentityCore <AppUser>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

            identityBuilder.AddEntityFrameworkStores <DataContext>();
            identityBuilder.AddSignInManager <SignInManager <AppUser> >();
            identityBuilder.AddDefaultTokenProviders();
        }
Exemplo n.º 13
0
        public override IServiceCollection AddModule(IServiceCollection services)
        {
            services.AddScoped <IUserStore <User>, UserStore>();
            services.AddScoped <IRoleStore <Role>, RoleStore>();
            //services.AddScoped<SignInManager<User>>();
            //services.AddScoped<UserManager<User>>();
            //services.AddScoped<RoleManager<Role>>();

            services.AddScoped <IIdentityContract, IdentityService>();

            //注入当前用户,替换Thread.CurrentPrincipal的作用
            services.AddTransient <IPrincipal>(provider =>
            {
                IHttpContextAccessor accessor = provider.GetService <IHttpContextAccessor>();
                return(accessor?.HttpContext?.User);
            });

            Action <IdentityOptions> identityOptionsAction = options =>
            {
                //登录
                options.SignIn.RequireConfirmedEmail = true;
                //密码
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                //用户
                options.User.RequireUniqueEmail = true;
                //锁定
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
            };
            IdentityBuilder builder = services.AddIdentity <User, Role>(identityOptionsAction);

            builder.AddDefaultTokenProviders();

            //添加Authentication服务
            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(jwt =>
            {
                string secret = AppSettingManager.Get("ESoftor:Jwt:Secret");
                jwt.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer      = AppSettingManager.Get("ESoftor:Jwt:Issuer"),
                    ValidAudience    = AppSettingManager.Get("ESoftor:Jwt:Audience"),
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret))
                };
                jwt.SecurityTokenValidators.Clear();
                //jwt.SecurityTokenValidators.Add(new OnlineUserJwtSecurityTokenHandler());//在线用户
            });
            return(services);
        }
        public static void AddIdentityStores(this IServiceCollection services)
        {
            var builder = services.AddIdentityCore <User>();

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <DataContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();
            builder.AddDefaultTokenProviders();
        }
Exemplo n.º 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityBuilder builder = services.AddIdentityCore <User>(opt =>
            {
                opt.Password.RequireDigit           = false;
                opt.Password.RequireLowercase       = false;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
                opt.Password.RequiredLength         = 4;

                opt.User.RequireUniqueEmail = true;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores <ApplicationDbContext>();
            builder.AddSignInManager <SignInManager <User> >();
            builder.AddRoleManager <RoleManager <IdentityRole> >();
            builder.AddDefaultTokenProviders();

            services.AddAuthorization(options =>
                                      options.AddPolicy("EmployerPolicy",
                                                        policy => policy.RequireRole("Employer")));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII
                                                                        .GetBytes(Configuration.GetSection("AppSettings:Key").Value)),
                    ValidateIssuer   = false,
                    ValidateAudience = false
                };
            });


            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("Default")));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSingleton <IEmail, MailJet>();
            services.AddSingleton <IStorageConnectionFactory, StorageConnectionFactory>(sp =>
            {
                CloudStorageOptionsDTO cloudStorageOptionsDTO = new CloudStorageOptionsDTO();
                cloudStorageOptionsDTO.ConnectionString       = Configuration["AzureBlobStorage:ConnectionString"];
                cloudStorageOptionsDTO.ProfilePicsContainer   = Configuration["AzureBlobStorage:BlobContainer"];
                return(new StorageConnectionFactory(cloudStorageOptionsDTO));
            });
            services.AddSingleton <ICloudStorage, AzureStorage>();
            services.Configure <EmailOptionsDTO>(Configuration.GetSection("MailJet"));

            services.AddAutoMapper(typeof(MapperProfiles));
        }
Exemplo n.º 16
0
        public static void AddTelegramClientIdentity(this IServiceCollection services)
        {
            IdentityBuilder builder = services.AddIdentityCore <UserEntity>();

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores <DarkDeedsTelegramClientContext>();

            services.AddScoped <UserManager <UserEntity> >();
        }
Exemplo n.º 17
0
        private static void AddIdentity(IServiceCollection services)
        {
            var builder         = services.AddIdentityCore <AppUser>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

            identityBuilder.AddEntityFrameworkStores <AuthenticationDbContext>();
            identityBuilder.AddSignInManager <SignInManager <AppUser> >();
            identityBuilder.AddDefaultTokenProviders();

            // Confirmation token timespan (confirm email, password reset)
            services.Configure <DataProtectionTokenProviderOptions>(o =>
                                                                    o.TokenLifespan = TimeSpan.FromHours(3));
        }
Exemplo n.º 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
            IdentityBuilder builder = services.AddIdentityCore <User>(opts => {
                opts.Password.RequiredLength         = 8;
                opts.Password.RequiredUniqueChars    = 0;
                opts.Password.RequireNonAlphanumeric = false;
                opts.Password.RequireUppercase       = false;
                opts.Password.RequireLowercase       = false;
            })
                                      .AddUserValidator <UniquePhoneNumber <User> >();

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <DataContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();
            builder.AddDefaultTokenProviders();

            services.AddAutoMapper();

            services.AddScoped <IAuthRepository, AuthRepository>();
            services.AddScoped <IDataRepository, DataRepository>();
            services.AddScoped <IPaymentRepository, PaymentRepository>();
            services.AddScoped <ITransactionRepository, TransactionRepository>();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddCors();
            services.AddMvc(options => {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(opt => {
                opt.SerializerSettings.ReferenceLoopHandling =
                    Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
        }
Exemplo n.º 19
0
        private void ConfigureServices(IdentityBuilder identityBuilder, IServiceCollection services)
        {
            identityBuilder.AddRoles <Role>();
            identityBuilder.AddEntityFrameworkStores <SqlServerAppContext>();
            identityBuilder.AddRoleValidator <RoleValidator <Role> >();
            identityBuilder.AddRoleManager <RoleManager <Role> >();
            identityBuilder.AddSignInManager <SignInManager <User> >();
            identityBuilder.AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes(Environment.GetEnvironmentVariable("SHARED_KEY"))
                    ),
                ValidateIssuer   = false,
                ValidateAudience = false,
            });

            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
            });

            services.AddMvc(opt =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();

                opt.Filters.Add(new AuthorizeFilter(policy));
                opt.AllowEmptyInputInBodyModelBinding = true;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                opt.SerializerSettings.DateFormatString      = "MM/dd/yyyy";
            });

            services.AddCors();
            services.AddAutoMapper();
            services.AddTransient <Seeder>();
            services.AddTransient <IUserResolver, UserResolver>();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IKidRepository, KidRepository>();
            services.AddScoped <IMemoryRepository, MemoryRepository>();
            services.AddScoped <IOrganizationRepository, OrganizationRepository>();
            services.AddScoped <IAwardRepository, AwardRepository>();
        }
        public static IdentityBuilder ConfigureIdentity(this IServiceCollection services)
        {
            IdentityBuilder builder = services.AddIdentity <ApplicationUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail        = true; // уникальный email
                config.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -._@+";
                config.SignIn.RequireConfirmedEmail   = false;
            });

            builder.AddEntityFrameworkStores <ApplicationDbContext>();
            builder.AddDefaultTokenProviders();

            return(builder);
        }
Exemplo n.º 21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public virtual void ConfigureServices(IServiceCollection services)
        {
            IdentityBuilder builder = services.AddIdentityCore <User>(opt =>
            {
                opt.Password.RequiredLength         = 6;
                opt.Password.RequireNonAlphanumeric = false;
                opt.SignIn.RequireConfirmedEmail    = false;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <BeepDbContext>();
            builder.AddDefaultTokenProviders();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();

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

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => ConfigureBearerToken(options, services));

            services.AddDbContext <BeepDbContext>(o =>
                                                  o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IAuthRepository, AuthRepository>();
            services.AddScoped <IArticleRepository, ArticleRepository>();
            services.AddTransient <IAuthorizationHandler, HasChangePermissionRequirementHandler>();
            services.AddTransient <IAuthorizationHandler, HasEnvironmentPermissionRequirementHandler>();
            services.AddSingleton <IPermissionsCache, PermissionsCache>();
            services.AddTransient <BeepBearerEvents>();
            services.AddTransient <IBeepMailer, Mailer>();
            services.AddScoped <IShoppingListRepo, ShoppingListRepo>();
            services.AddHostedService <DemoUserCleanup>();
            services.AddHostedService <PermissionsCacheCleanup>();

            if (_environment.IsDevelopment())
            {
                services.AddTransient <IMailerClient, SmtpMailerClient>();
            }
            else
            {
                services.AddTransient <IMailerClient, SendGridMailerClient>();
            }
        }
Exemplo n.º 22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <BWDbContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DBConnection")));
            IdentityBuilder builder = services.AddIdentityCore <ApplicationUser>(opt => {
                opt.Password.RequireDigit           = false;
                opt.Password.RequiredLength         = 1;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
                opt.Password.RequireLowercase       = false;
            });

            builder = new IdentityBuilder(builder.UserType, builder.Services);
            builder.AddRoles <IdentityRole>();
            builder.AddRoleValidator <RoleValidator <IdentityRole> >();
            builder.AddRoleManager <RoleManager <IdentityRole> >();
            builder.AddSignInManager <SignInManager <ApplicationUser> >();
            builder.AddEntityFrameworkStores <BWDbContext>();
            builder.AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    //ValidIssuer = Configuration["Jwt:Issuer"],
                    //ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

            services.AddMvc(options => {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(opt => {
                opt.SerializerSettings.ReferenceLoopHandling =
                    Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
            services.AddCors();
            services.AddAutoMapper(typeof(Startup));
        }
        public static void ConfigureIdentity(this IServiceCollection services)
        {
            var builder = services.AddIdentityCore <Usuario>(option =>
            {
                option.Password.RequireDigit           = true;
                option.Password.RequireLowercase       = false;
                option.Password.RequireUppercase       = false;
                option.Password.RequireNonAlphanumeric = false;
                option.Password.RequiredLength         = 10;
                option.User.RequireUniqueEmail         = true;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);

            builder.AddEntityFrameworkStores <RepositoryContext>();
            builder.AddDefaultTokenProviders();
        }
Exemplo n.º 24
0
        public static void ConfigureIdentity(this IServiceCollection services)
        {
            IdentityBuilder builder = services.AddIdentityCore <User>(opts => {
                opts.SignIn.RequireConfirmedEmail    = true;
                opts.Lockout.MaxFailedAccessAttempts = 10;
                opts.User.RequireUniqueEmail         = true;
            });

            // .AddUserValidator<UniqueEmail<User>>();

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <DefaultDataContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();
            builder.AddDefaultTokenProviders();
        }
Exemplo n.º 25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo("/usr/AngularCore31/keys/"))
            .ProtectKeysWithCertificate(new X509Certificate2("./wwwroot/AngularCore31.pfx", "Abc 123"));

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseMySql(
                                                             Configuration.GetConnectionString("DefaultConnection")));

            // services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
            //     .AddEntityFrameworkStores<ApplicationDbContext>();

            IdentityBuilder identityBuilder = services.AddIdentity <ApplicationUser, IdentityRole>(options => {
            });

            identityBuilder.AddEntityFrameworkStores <ApplicationDbContext>();
            identityBuilder.AddDefaultUI();
            identityBuilder.AddDefaultTokenProviders();


            services.AddIdentityServer()
            .AddApiAuthorization <ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
            .AddIdentityServerJwt();

            services.AddLocalization(options => {
                options.ResourcesPath = "Resources";
            });

            services.AddControllersWithViews()
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options => {
                options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource));
            });

            services.AddRazorPages();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
Exemplo n.º 26
0
        public static void AddPayIdentityInit(this IServiceCollection services)
        {
            IdentityBuilder builder = services.AddIdentityCore <User>(opt =>
            {
                opt.Password.RequireDigit           = false;
                opt.Password.RequiredLength         = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
                opt.Password.RequireLowercase       = false;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <PayDelDbContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();
            builder.AddDefaultTokenProviders();
        }
Exemplo n.º 27
0
        public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
        {
            var builder = services.AddIdentityCore <AppUser>(opt =>
            {
                opt.SignIn.RequireConfirmedEmail    = true;
                opt.Lockout.MaxFailedAccessAttempts = 3;                       //the number of failed login attempts allowed before the account is locked out.
                opt.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(1); // Specifies the amount of the time the account should be locked.
            });

            builder = new IdentityBuilder(builder.UserType, builder.Services);
            builder.AddRoles <IdentityRole>();
            builder.AddEntityFrameworkStores <AppIdentityDbContext>(); //Retrieve user info
            builder.AddSignInManager <SignInManager <AppUser> >();
            builder.AddDefaultTokenProviders();                        //Otherwise => generate tokens for email confirmation, password reset, two factor authentication

            /**
             * Password Options Rules
             **/
            services.Configure <IdentityOptions>(opt =>
            {
                opt.Password.RequiredLength      = 10;
                opt.Password.RequiredUniqueChars = 3;
            });

            /**
             *  Add JWT Token
             **/
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,    //Validate signature of the token
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:Key"])),
                    ValidIssuer      = config["Token:Issuer"],
                    ValidateIssuer   = true,  //Validate the server that generates the token.
                    ValidateAudience = false, //Validate the recipient of the token is authorized to receive
                    ValidateLifetime = true   // ValidateLifetime = true//Check if the token is not expired and the signing key of the issuer is valid
                };
            });

            return(services);
        }
Exemplo n.º 28
0
        public static void UseIdentity(IServiceCollection services, IConfiguration configuration)
        {
            var identityBuilder = services.AddIdentityCore <IdentityAppUser>(opt =>
            {
                opt.Password.RequireDigit           = false;
                opt.Password.RequiredLength         = 5;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
                opt.Password.RequireLowercase       = false;
            });

            identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(IdentityRole), identityBuilder.Services);
            identityBuilder.AddEntityFrameworkStores <IdentityAppContext>();
            identityBuilder.AddDefaultTokenProviders();

            services.AddIdentity <IdentityAppUser, IdentityRole>()
            .AddEntityFrameworkStores <IdentityAppContext>()
            .AddDefaultTokenProviders();

            //Adding JWT Tokens
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
            services.AddAuthentication(opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = configuration["JwtIssuer"],
                    ValidAudience    = configuration["JwtIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtKey"])),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire
                };
            });

            services.AddDbContext <IdentityAppContext>(options => options.UseSqlServer(configuration.GetConnectionString("IdentityDB")));
        }
Exemplo n.º 29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

            services.AddMediatR(typeof(GetPosts.Handler).Assembly);
            services.AddAutoMapper(typeof(GetPosts.Handler));


            services.AddControllers();

            var builder = services.AddIdentityCore <AppUser>(opt =>
            {
                opt.Password.RequireDigit           = true;
                opt.Password.RequiredLength         = 6;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = true;
                opt.SignIn.RequireConfirmedEmail    = false;
            });
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

            identityBuilder.AddEntityFrameworkStores <DataContext>();
            identityBuilder.AddSignInManager <SignInManager <AppUser> >();
            identityBuilder.AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII
                                                                        .GetBytes(Configuration.GetSection("Token").Value)),
                    ValidateIssuer   = false,
                    ValidateAudience = false
                };
            });

            services.AddScoped(typeof(IRepository <>), typeof(Repository <>));
            services.AddScoped <IAuthRepository, AuthRepository>();
            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IUserAccessor, UserAccessor>();
        }
Exemplo n.º 30
0
        public static void Configure(IServiceCollection services)
        {
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequiredLength = 4;
                options.User.RequireUniqueEmail = true;
            });

            services.AddTransient <IPasswordHasher <User>, PasswordHasher <User> >();
            services.AddTransient <ILookupNormalizer, UpperInvariantLookupNormalizer>();
            services.AddTransient <IdentityErrorDescriber>();

            services.AddTransient <IRoleStore <Role>, RoleStore <Role> >();
            services.AddTransient <IUserStore <User>, UserStore <User, Role, UserRole, UserClaim> >();
            services.AddTransient <UserManager <User>, ApplicationUserManager>();

            var identityBuilder = new IdentityBuilder(typeof(User), typeof(User), services);

            identityBuilder.AddDefaultTokenProviders();
        }