示例#1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);

            services.AddDbContext <DataContext>(x =>
                                                x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            var identityBuilder = services.AddIdentityCore <User>(options =>
            {
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireDigit           = false;
            });

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

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };

                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("/messagesHub")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

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

            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 = ReferenceLoopHandling.Ignore);
            services.AddCors();
            services.AddScoped <IAuthRepository, AuthRepository>();
            services.AddSingleton <ITokenService, JwtService>();
            services.AddSignalR();

            services.AddSingleton <IUserIdProvider, UserIdProvider>();
            services.AddSingleton <IPasswordService, PasswordService>();
            services.AddTransient <Seed>();
            services.AddScoped <IDatingRepository, DatingRepository>();
            services.AddAutoMapper();
            services.Configure <CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));
            services.AddSingleton <ICloudinaryService, CloudinaryService>();
            services.AddScoped <LogUserActivityFilter>();
            services.AddScoped <IAdminRepository, AdminRepository>();
        }
示例#2
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.UseLazyLoadingProxies();
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000").AllowCredentials();
                });
            });
            services.AddMediatR(typeof(List.Handler).Assembly);
            services.AddAutoMapper(typeof(List.Handler));
            services.AddSignalR();
            services.AddControllers(opt =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            }).AddFluentValidation(cfg =>
            {
                cfg.RegisterValidatorsFromAssemblyContaining <Create>();
            });

            var builder         = services.AddIdentityCore <AppUser>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

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

            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("IsActivityHost", policy =>
                {
                    policy.Requirements.Add(new IsHostRequirement());
                });
            });
            services.AddTransient <IAuthorizationHandler, IsHostRequirementHandler>();

            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
                };
                opt.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path        = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chat")))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IUserAccessor, UserAccessor>();
            services.AddScoped <IPhotoAccessor, PhotoAccessor>();
            services.Configure <CloudinarySettings>(Configuration.GetSection("Cloudinary"));
        }
示例#3
0
 public static IdentityBuilder UseCassandraStores <TSession>(this IdentityBuilder builder)
     where TSession : class, ISession
 => builder
 .AddCassandraUserStore <TSession>()
 .AddCassandraRoleStore <TSession>();
示例#4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSignalR();
            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            // add Entity framework with migrations assembly for the project "OthelloServer"
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                                                                              b => b.MigrationsAssembly("OthelloServer")));

            // add identity
            // Injects UserManager
            IdentityBuilder builder = services.AddIdentityCore <AppUser>(o =>
            {
                o.User.RequireUniqueEmail = true;
                // configure identity options
                o.Password.RequireDigit           = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 6;
            }).AddEntityFrameworkStores <ApplicationDbContext>()
                                      .AddDefaultTokenProviders();


            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                                        .RequireAuthenticatedUser()
                                        .Build();
            });

            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(jwtOptions =>
            {
                jwtOptions.SaveToken    = true;
                jwtOptions.ClaimsIssuer = Configuration["Authentication:Issuer"];
                jwtOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = Configuration["JwtAuthentication:Issuer"],

                    ValidateAudience = true,
                    ValidAudience    = Configuration["JwtAuthentication:Audience"],

                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(
                        Encoding.ASCII.GetBytes(Configuration["JwtAuthentication:SecretKey"])),

                    RequireExpirationTime = false,
                    ValidateLifetime      = true,
                    ClockSkew             = TimeSpan.Zero
                };
                // We have to hook the OnMessageReceived event in order to
                // allow the JWT authentication handler to read the access
                // token from the query string when a WebSocket or
                // Server-Sent Events request comes in.
                jwtOptions.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("/socket/seek") ||
                             path.StartsWithSegments("/socket/game")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddSingleton(Configuration);

            SeekPool pool = new SeekPool();

            services.AddSingleton(pool);


            // Change to use Name as the user identifier for SignalR
            // WARNING: This requires that the source of your JWT token
            // ensures that the Name claim is unique!
            // If the Name claim isn't unique, users could receive messages
            // intended for a different user!
            //services.AddSingleton<IUserIdProvider, NameUserIdProvider>();

            // Change to use email as the user identifier for SignalR
            // services.AddSingleton<IUserIdProvider, EmailBasedUserIdProvider>();

            // WARNING: use *either* the NameUserIdProvider *or* the
            // EmailBasedUserIdProvider, but do not use both.
        }
示例#5
0
        public static IdentityBuilder AddCloudscribeIdentity(
            this IServiceCollection services,
            Action <IdentityOptions> setupAction = null
            )
        {
            //services.AddScoped<IAuthenticationHandlerProvider, SiteAuthenticationHandlerProvider>();

            // Services used by identity
            // this will change in 2.0 AddCookieAuthentication => AddCookie
            //https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity/IdentityServiceCollectionExtensions.cs
            //services.AddAuthenticationCore(options =>
            //{
            //    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
            //    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
            //    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
            //});

            services.AddSingleton <IOptionsMonitor <CookieAuthenticationOptions>, SiteCookieAuthenticationOptions>();
            //services.AddSingleton<IOptionsSnapshot<CookieAuthenticationOptions>, SiteCookieAuthenticationOptionsPreview>();

            services.AddSingleton <IOptionsMonitor <FacebookOptions>, SiteFacebookOptions>();
            services.AddSingleton <IOptionsMonitor <GoogleOptions>, SiteGoogleOptions>();
            services.AddSingleton <IOptionsMonitor <MicrosoftAccountOptions>, SiteMicrosoftAccountOptions>();
            services.AddSingleton <IOptionsMonitor <TwitterOptions>, SiteTwitterOptions>();
            services.AddSingleton <IOptionsMonitor <OpenIdConnectOptions>, SiteOpenIdConnectOptions>();

            services.TryAddSingleton <IIdentityOptionsFactory, DefaultIdentityOptionsFactory>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                options.DefaultChallengeScheme    = IdentityConstants.ApplicationScheme;
                options.DefaultSignInScheme       = IdentityConstants.ExternalScheme;
            })
            .AddCookie(IdentityConstants.ApplicationScheme, o =>
            {
                o.LoginPath = new PathString("/Account/Login");
                //o.Events = new CookieAuthenticationEvents
                //{
                //    OnValidatePrincipal = SiteAuthCookieValidator.ValidatePrincipalAsync
                //};
            })
            .AddCookie(IdentityConstants.ExternalScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.ExternalScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddCookie(IdentityConstants.TwoFactorRememberMeScheme,
                       o => o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme
                       )
            .AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.TwoFactorUserIdScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddFacebook(o =>
            {
                o.AppId     = "placeholder";
                o.AppSecret = "placeholder";
            })
            .AddGoogle(o =>
            {
                o.ClientId     = "placeholder";
                o.ClientSecret = "placeholder";
                o.SignInScheme = IdentityConstants.ExternalScheme;
                //o.ClaimActions
            })
            .AddMicrosoftAccount(o =>
            {
                o.ClientId     = "placeholder";
                o.ClientSecret = "placeholder";
            })
            .AddTwitter(o =>
            {
                o.ConsumerKey    = "placeholder";
                o.ConsumerSecret = "placeholder";
            })
            .AddOpenIdConnect(o =>
            {
                o.ClientId     = "placeholder";
                o.ClientSecret = "placeholder";
                o.Authority    = "https://placeholder.com";

                //o.GetClaimsFromUserInfoEndpoint = true;


                o.ResponseType = "code id_token";

                //o.Scope.Add("idserverapi");
                //o.Scope.Add("profile");
                o.GetClaimsFromUserInfoEndpoint = true;
                o.SaveTokens = true;
            })

            ;


            services.TryAddSingleton <ICaptureOidcTokens, NoopOidcTokenCapture>();
            services.TryAddSingleton <ICookieAuthTicketStoreProvider, NoopCookieAuthTicketStoreProvider>();


            // Services used by identity
            services.AddSingleton <IOptions <IdentityOptions>, SiteIdentityOptionsResolver>();

            services.AddScoped <IUserClaimsPrincipalFactory <SiteUser>, SiteUserClaimsPrincipalFactory <SiteUser, SiteRole> >();
            services.TryAddScoped <IPasswordHasher <SiteUser>, SitePasswordHasher <SiteUser> >();
            //services.TryAddScoped<SiteSignInManager<SiteUser>, SiteSignInManager<SiteUser>>();

            services.TryAddScoped <SignInManager <SiteUser>, SignInManager <SiteUser> >();

            //services.TryAddSingleton<SiteAuthCookieValidator, SiteAuthCookieValidator>();
            services.TryAddSingleton <ICookieAuthRedirector, ApiAwareCookieAuthRedirector>();
            //services.TryAddScoped<SiteCookieAuthenticationEvents, SiteCookieAuthenticationEvents>();
            services.TryAddScoped <ISocialAuthEmailVerfificationPolicy, DefaultSocialAuthEmailVerfificationPolicy>();

            services.TryAddScoped <ISiteAccountCapabilitiesProvider, DefaultSiteAcountCapabilitiesProvider>();
            services.TryAddScoped <IProcessAccountLoginRules, DefaultAccountLoginRulesProcessor>();

            services.AddSingleton <IAntiforgeryTokenStore, SiteAntiforgeryTokenStore>();

            services.AddAuthentication(options =>
            {
                // This is the Default value for ExternalCookieAuthenticationScheme
                //commented out 2017-07-25 breaking change in 2.0
                //options.SignInScheme = new IdentityCookieOptions().ExternalCookieAuthenticationScheme;
            });

            // Hosting doesn't add IHttpContextAccessor by default
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // Identity services
            //commented out 20170-07-25 breaking change in 2.0
            //services.TryAddSingleton<IdentityMarkerService>();

            services.TryAddScoped <IUserValidator <SiteUser>, UserValidator <SiteUser> >();
            services.TryAddScoped <IPasswordValidator <SiteUser>, PasswordValidator <SiteUser> >();
            services.TryAddScoped <ILookupNormalizer, UpperInvariantLookupNormalizer>();
            services.TryAddScoped <IRoleValidator <SiteRole>, RoleValidator <SiteRole> >();
            // No interface for the error describer so we can add errors without rev'ing the interface
            services.TryAddScoped <IdentityErrorDescriber>();
            services.TryAddScoped <ISecurityStampValidator, SecurityStampValidator <SiteUser> >();


            services.AddScoped <UserEvents, UserEvents>();

            services.TryAddScoped <ICustomClaimProvider, DoNothingCustomClaimProvider>();

            if (setupAction != null)
            {
                services.Configure(setupAction);
            }

            var builder = new IdentityBuilder(typeof(SiteUser), typeof(SiteRole), services);

            builder.AddUserStore <UserStore <SiteUser> >()
            .AddRoleStore <RoleStore <SiteRole> >()
            .AddUserManager <SiteUserManager <SiteUser> >()
            .AddRoleManager <SiteRoleManager <SiteRole> >()
            ;

            var dataProtectionProviderType = typeof(DataProtectorTokenProvider <SiteUser>);
            var phoneNumberProviderType    = typeof(PhoneNumberTokenProvider <SiteUser>);
            var emailTokenProviderType     = typeof(EmailTokenProvider <SiteUser>);
            var authenticatorProviderType  = typeof(AuthenticatorTokenProvider <SiteUser>);

            services.Configure <TokenOptions>(options =>
            {
                options.ProviderMap[TokenOptions.DefaultProvider]              = new TokenProviderDescriptor(dataProtectionProviderType);
                options.ProviderMap[TokenOptions.DefaultEmailProvider]         = new TokenProviderDescriptor(emailTokenProviderType);
                options.ProviderMap[TokenOptions.DefaultPhoneProvider]         = new TokenProviderDescriptor(phoneNumberProviderType);
                options.ProviderMap[TokenOptions.DefaultAuthenticatorProvider] = new TokenProviderDescriptor(authenticatorProviderType);
            });
            services.TryAddTransient(dataProtectionProviderType);
            services.TryAddTransient(emailTokenProviderType);
            services.TryAddTransient(phoneNumberProviderType);
            services.TryAddTransient(authenticatorProviderType);


            services.TryAddScoped <IIdentityServerIntegration, NotIntegratedIdentityServerIntegration>();

            services.AddTransient <SiteAuthCookieEvents>();
            services.TryAddTransient <ISiteAuthCookieEvents, SiteAuthCookieEvents>();
            services.AddTransient <OidcTokenEndpointService>();
            services.AddScoped <cloudscribe.Core.Identity.IOidcHybridFlowHelper, cloudscribe.Core.Identity.HybridFlowHelper>();

            return(builder);

            //return services;
        }
示例#6
0
        public static IdentityBuilder AddCloudscribeIdentity(
            this IServiceCollection services,
            Action <IdentityOptions> setupAction = null
            )
        {
            services.AddSingleton <IOptions <IdentityOptions>, SiteIdentityOptionsResolver>();

            //services.AddIdentity<SiteUser, SiteRole>()
            //    .AddUserStore<UserStore<SiteUser>>()
            //    .AddRoleStore<RoleStore<SiteRole>>()
            //    .AddUserManager<SiteUserManager<SiteUser>>()
            //    .AddRoleManager<SiteRoleManager<SiteRole>>()
            //    .AddDefaultTokenProviders()
            //    ;

            // Services used by identity

            services.AddScoped <IUserClaimsPrincipalFactory <SiteUser>, SiteUserClaimsPrincipalFactory <SiteUser, SiteRole> >();
            services.AddScoped <IPasswordHasher <SiteUser>, SitePasswordHasher <SiteUser> >();
            services.AddScoped <SiteSignInManager <SiteUser>, SiteSignInManager <SiteUser> >();
            services.AddSingleton <SiteAuthCookieValidator, SiteAuthCookieValidator>();
            services.AddScoped <SiteCookieAuthenticationEvents, SiteCookieAuthenticationEvents>();
            services.AddSingleton <IAntiforgeryTokenStore, SiteAntiforgeryTokenStore>();

            services.AddAuthentication(options =>
            {
                // This is the Default value for ExternalCookieAuthenticationScheme
                options.SignInScheme = new IdentityCookieOptions().ExternalCookieAuthenticationScheme;
            });

            // Hosting doesn't add IHttpContextAccessor by default
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // Identity services
            services.TryAddSingleton <IdentityMarkerService>();
            services.TryAddScoped <IUserValidator <SiteUser>, UserValidator <SiteUser> >();
            services.TryAddScoped <IPasswordValidator <SiteUser>, PasswordValidator <SiteUser> >();
            //services.TryAddScoped<IPasswordHasher<SiteUser>, PasswordHasher<SiteUser>>();
            services.TryAddScoped <ILookupNormalizer, UpperInvariantLookupNormalizer>();
            services.TryAddScoped <IRoleValidator <SiteRole>, RoleValidator <SiteRole> >();
            // No interface for the error describer so we can add errors without rev'ing the interface
            services.TryAddScoped <IdentityErrorDescriber>();
            services.TryAddScoped <ISecurityStampValidator, SecurityStampValidator <SiteUser> >();
            //services.TryAddScoped<IUserClaimsPrincipalFactory<SiteUser>, UserClaimsPrincipalFactory<SiteUser, SiteRole>>();
            //services.TryAddScoped<UserManager<SiteUser>, UserManager<SiteUser>>();
            //services.TryAddScoped<SignInManager<SiteUser>, SignInManager<SiteUser>>();
            //services.TryAddScoped<RoleManager<SiteRole>, RoleManager<SiteRole>>();

            services.AddScoped <ICustomClaimProvider, DoNothingCustomClaimProvider>();

            if (setupAction != null)
            {
                services.Configure(setupAction);
            }

            var builder = new IdentityBuilder(typeof(SiteUser), typeof(SiteRole), services);

            builder.AddUserStore <UserStore <SiteUser> >()
            .AddRoleStore <RoleStore <SiteRole> >()
            .AddUserManager <SiteUserManager <SiteUser> >()
            .AddRoleManager <SiteRoleManager <SiteRole> >()
            ;

            var dataProtectionProviderType = typeof(DataProtectorTokenProvider <SiteUser>);
            var phoneNumberProviderType    = typeof(PhoneNumberTokenProvider <SiteUser>);
            var emailTokenProviderType     = typeof(EmailTokenProvider <SiteUser>);

            services.Configure <TokenOptions>(options =>
            {
                options.ProviderMap[TokenOptions.DefaultProvider]      = new TokenProviderDescriptor(dataProtectionProviderType);
                options.ProviderMap[TokenOptions.DefaultEmailProvider] = new TokenProviderDescriptor(emailTokenProviderType);
                options.ProviderMap[TokenOptions.DefaultPhoneProvider] = new TokenProviderDescriptor(phoneNumberProviderType);
            });
            services.AddTransient(dataProtectionProviderType);
            services.AddTransient(emailTokenProviderType);
            services.AddTransient(phoneNumberProviderType);



            return(builder);

            //return services;
        }
        /// <summary>
        /// 添加Mozlite框架存储服务。
        /// </summary>
        /// <typeparam name="TUserClaim">用户声明类型。</typeparam>
        /// <typeparam name="TUserLogin">用户登陆声明类型。</typeparam>
        /// <typeparam name="TUserRole">用户所在组声明类型。</typeparam>
        /// <typeparam name="TRoleClaim">用户组声明类型。</typeparam>
        /// <typeparam name="TUserToken">用户标识。</typeparam>
        /// <param name="builder">Identity构建实例。</param>
        /// <returns>返回Identity构建实例。</returns>
        public static IdentityBuilder AddIdentityStores <TUserClaim, TRoleClaim, TUserRole, TUserLogin, TUserToken>(this IdentityBuilder builder)
            where TUserClaim : IdentityUserClaim, new()
            where TRoleClaim : IdentityRoleClaim, new()
            where TUserRole : IdentityUserRole, new()
            where TUserLogin : IdentityUserLogin, new()
            where TUserToken : IdentityUserToken, new()
        {
            var userStoreType = typeof(IdentityUserStore <, , , , ,>).MakeGenericType(builder.UserType, builder.RoleType, typeof(TUserClaim), typeof(TUserLogin), typeof(TUserRole), typeof(TUserToken));
            var roleStoreType = typeof(IdentityIdentityRoleStore <,>).MakeGenericType(builder.RoleType, typeof(TRoleClaim));

            return(builder.AddIdentityStores(userStoreType, roleStoreType));
        }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <PhotoSettings>(Configuration.GetSection("PhotoSettings"));
            services.AddDbContext <VegaDbContext>(options =>
                                                  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddScoped <IVehicleRepository, VehicleRepository>();
            services.AddScoped <IPhotoRepository, PhotoRepository>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddScoped <IJwtFactory, JwtFactory>();

            //===== identity (registration model configuration)====
            var builder = services.AddIdentityCore <AppUser>(o =>
            {
                // configure identity options
                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(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores <VegaDbContext>().AddDefaultTokenProviders();
            //===JWT validation properties /jwt wire up
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];// or smth like ['Issuer']
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });
            //===== token parameters (Json Web TOKEN)
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = _signingKey,
                // if u want to configure expiration time configure JwtIssuer first
                RequireExpirationTime = false,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero
            };

            //=====
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;       //token params assign
                configureOptions.SaveToken = true;
            });
            services.AddAutoMapper();
            services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>());

            services.AddScoped <SignInManager <AppUser>, SignInManager <AppUser> >();
            services.AddScoped <RoleManager <IdentityRole>, RoleManager <IdentityRole> >();
        }
示例#9
0
 public static IdentityBuilder AddIdentityDataContext(this IdentityBuilder identityBuilder)
 {
     return(identityBuilder.AddEntityFrameworkStores <ApplicationDbContext>());
 }
示例#10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add MediatR
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>));
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPerformanceBehaviour <,>));
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestValidationBehavior <,>));
            services.AddMediatR(typeof(GetProductQueryHandler).GetTypeInfo().Assembly);
            services.AddMediatR(typeof(AuthenticateUserQuery).GetTypeInfo().Assembly);
            services.AddSingleton <IJwtFactory, JwtFactory>();

            services.AddDbContext <PharmalinaDbContext>(options =>
                                                        options.UseSqlServer(Configuration.GetConnectionString("PharmalinaDb"), b => b.MigrationsAssembly("Pharmalina.WebUI")));

            // Customise default API behavour
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });

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

            // Swagger configuration
            services.AddSwaggerDocument(configure =>
            {
                configure.PostProcess = document =>
                {
                    document.Info.Version     = "v1";
                    document.Info.Title       = "Pharmalina API";
                    document.Info.Description = "ASP.NET Core Web API";
                };
            });

            // Register the ConfigurationBuilder instance of FacebookAuthSettings
            services.Configure <FacebookAuthSettings>(Configuration.GetSection(nameof(FacebookAuthSettings)));

            services.TryAddTransient <IHttpContextAccessor, HttpContextAccessor>();

            // configure strongly typed settings objects
            var PharmalinaSecretSection = Configuration.GetSection("PharmalinaSecret");

            services.Configure <secretToken>(PharmalinaSecretSection);

            // configure jwt authentication
            string PharmalinaSecret = PharmalinaSecretSection.Get <secretToken>().ToString();

            key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(PharmalinaSecret));

            // jwt wire up
            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            });

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = key,

                RequireExpirationTime = false,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;
            });

            // api user claim policy
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
            });

            // add identity
            var builder = services.AddIdentityCore <User>(o =>
            {
                // configure identity options
                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(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores <PharmalinaDbContext>().AddDefaultTokenProviders();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
示例#11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Util.baseApiRegistration = Configuration["BaseUrl"];

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
                                                         .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));


            services.AddTransient <ApplicationDbContext>();

            IdentityBuilder builder = services.AddDefaultIdentity <IdentityUser>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 4;

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

            builder = new IdentityBuilder(builder.UserType, builder.Services);
            builder.AddRoles <IdentityRole>();
            builder.AddEntityFrameworkStores <ApplicationDbContext>();
            builder.AddSignInManager <SignInManager <IdentityUser> >();


            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(60);
            });

            services.AddAutoMapper(typeof(Startup));

            services.AddControllersWithViews()
            .AddRazorRuntimeCompilation();

            services.AddMvc()
            .AddNToastNotifyToastr()
            .AddMvcOptions(options => options.EnableEndpointRouting = false);


            services.AddHttpContextAccessor();

            services.AddHttpClient("cartech", client =>
            {
                var serviceProvider = services.BuildServiceProvider();

                var httpContextAccessor = serviceProvider.GetService <IHttpContextAccessor>();

                var bearerToken = httpContextAccessor.HttpContext.Request
                                  .Headers["Authorization"]
                                  .FirstOrDefault(h => h.StartsWith("bearer ", StringComparison.InvariantCultureIgnoreCase));

                if (bearerToken != null)
                {
                    client.DefaultRequestHeaders.Add("Authorization", bearerToken);
                }

                client.BaseAddress = new Uri(Util.baseApiRegistration);
            });

            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
        }
示例#12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var migrationAssembly = "ProAgil.Repository"; // typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <ProAgilContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), sql => sql.MigrationsAssembly(migrationAssembly)));

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

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

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // validação pela assinatura da chave do emissor
                    ValidateIssuerSigningKey = true,
                    // chave do emissor
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer   = false,
                    ValidateAudience = false
                };
            }
                          );

            services.AddMvc(options =>
            {
                // política para autorizar acesso a controlers
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(opt => opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            //Injetar Dependecias
            services.AddScoped <IProAgilRepository <RedeSocial>, ProAgilRepository <RedeSocial> >();
            services.AddScoped <IProAgilRepository <Evento>, ProAgilRepository <Evento> >();
            services.AddScoped <IProAgilRepository <Lote>, ProAgilRepository <Lote> >();
            services.AddScoped <IProAgilRepository <Palestrante>, ProAgilRepository <Palestrante> >();
            services.AddAutoMapper();
            services.AddApiVersioning(options =>
            {
                options.UseApiBehavior = false;
                // assume valor padrão se não específicado
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(majorVersion: 2, minorVersion: 0);
                // pode ser usado para criar diferentes versões de métodos API sem ter que criar outra URL
                // bastando adicionar no header da requisição o key abaixo e valor definido no método
                options.ApiVersionReader = new HeaderApiVersionReader("api-version");
                // informa no cabeçalho se versão está obsoleta
                options.ReportApiVersions = true;
                //   options.ApiVersionReader = new  ApiVersionHeader("");
            });

            services.AddVersionedApiExplorer(options =>
            {
                // v -> versão VV -> major e minor version V -> Path Url
                options.GroupNameFormat           = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });

            services.AddSwaggerGen(
                c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "Documentação API Eventos Swagger",
                    Description    = "A simple example ASP.NET Core Web API",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact        = new OpenApiContact
                    {
                        Name  = "Shayne Boyer",
                        Email = string.Empty,
                        Url   = new Uri("https://twitter.com/spboyer"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url  = new Uri("https://example.com/license"),
                    }
                });
                c.SwaggerDoc("v2", new OpenApiInfo
                {
                    Version        = "v2",
                    Title          = "Documentação API Eventos Swagger",
                    Description    = "A simple example ASP.NET Core Web API",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact        = new OpenApiContact
                    {
                        Name  = "Shayne Boyer",
                        Email = string.Empty,
                        Url   = new Uri("https://twitter.com/spboyer"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url  = new Uri("https://example.com/license"),
                    }
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In          = ParameterLocation.Header,
                    Description = "Por favor coloque o valor 'Bearer' seguido de um espaço em branco e depois o valor do token no formato JWT!",
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.ApiKey
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    { new OpenApiSecurityScheme {
                          Reference = new OpenApiReference {
                              Type = ReferenceType.SecurityScheme, Id = "Bearer"
                          }
                      }, new string[] { } }
                });
                //  c.DocumentFilter<SwaggerExcludeFilter>(); // para ocultar models DTO na tela pricipal add o nome da model dentro da classe.
            });

            services.AddCors();
        }
示例#13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //order is not important in this method... but it is in the one below void Configure(IAppli....)
            services.AddDbContext <DataContext>(opt =>
            {
                opt.UseLazyLoadingProxies();
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000");
                });
            });
            // Any class from the assembly where I have it (any class inside Application project)
            services.AddMediatR(typeof(List.Handler).Assembly);
            services.AddAutoMapper(typeof(List.Handler));
            services.AddMvc(
                opt =>
            {
                // this defines that every request must be authenticated
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            }
                )
            .AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining <Create>())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //ASP.NET Core Identity Setup
            var builder         = services.AddIdentityCore <AppUser>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

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

            // Add security policy for IsHost
            services.AddAuthorization(opt => opt.AddPolicy("IsActivityHost", policy =>
            {
                policy.Requirements.Add(new IsHostRequirement());
            }));

            services.AddTransient <IAuthorizationHandler, IsHostRequirementHandler>();

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"])); // move to the server and make match with the one in JwtGenerator.cs

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

            //Custom interfaces and implementations
            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IUserAccessor, UserAccessor>();
            services.AddScoped <IPhotoAccessor, PhotoAccessor>();

            //Cloudinary settings
            services.Configure <CloudinarySettings>(Configuration.GetSection("Cloudinary"));
        }
示例#14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // read from appsettings.json

            // registra il provider EF per SqlServer
            services.AddDbContext <DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // ASP.NET Core Identity configuration
            IdentityBuilder builder = services.AddIdentityCore <User>(opt =>
            {
                opt.Password.RequireDigit           = false;
                opt.Password.RequiredLength         = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            // Identity utilizza EF come store
            builder.AddEntityFrameworkStores <DataContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();

            // configurazione autenticazione delle Request HTTP tramite token JWT
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).
            AddJwtBearer(options => {
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            // policy based authorization
            services.AddAuthorization(opt => {
                opt.AddPolicy("RequireAdminRole", pol => pol.RequireRole("Admin"));
                opt.AddPolicy("ModeratePhotoRole", pol => pol.RequireRole("Admin", "Moderator"));
                opt.AddPolicy("VipOnly", pol => pol.RequireRole("VIP"));
            });

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }
                            )
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson(opt => {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            // enable cross domain calls to API
            services.AddCors();

            // cloudinary settings (utilizzato per lo storage di file sul cloud provider)
            services.Configure <CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));

            // automapper
            //Mapper.Reset();
            services.AddAutoMapper(typeof(DatingRepository).Assembly);

            // registra la classe per il popolamento iniziale del DB
            //services.AddTransient<Seed>();

            // vengono registrati i repository con lifetime per HTTP request
            //services.AddScoped<IAuthRepository, AuthRepository>();
            services.AddScoped <IDatingRepository, DatingRepository>();

            services.AddScoped <LogUserActivity>();
        }
 /// <summary>
 /// 添加Mozlite框架存储服务。
 /// </summary>
 /// <param name="builder">Identity构建实例。</param>
 /// <typeparam name="TUserStore">用户存储类型。</typeparam>
 /// <typeparam name="TRoleStore">用户组存储类型。</typeparam>
 /// <returns>返回Identity构建实例。</returns>
 public static IdentityBuilder AddIdentityStores <TUserStore, TRoleStore>(this IdentityBuilder builder)
 {
     return(builder.AddIdentityStores(typeof(TUserStore), typeof(TRoleStore)));
 }
示例#16
0
 /// <summary>
 /// 重写以实现 AddIdentity 之后的构建逻辑
 /// </summary>
 /// <param name="builder"></param>
 /// <returns></returns>
 protected override IdentityBuilder OnIdentityBuild(IdentityBuilder builder)
 {
     //如需要昵称唯一,启用下面这个验证码
     //builder.AddUserValidator<UserNickNameValidator<User, int>>();
     return(builder.AddDefaultTokenProviders());
 }
示例#17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add a CORS policy to allow requests from localhost:3000 (React app).
            services.AddCors(opt => {
                opt.AddPolicy("CorsPolicy", policy => {
                    policy
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithExposedHeaders("WWW-Authenticate")
                    .WithOrigins("http://localhost:3000")
                    .AllowCredentials();     // Allows SignalR to connect
                });
            });

            services.AddMediatR(typeof(Application.Activities.List.Handler).Assembly);
            services.AddAutoMapper(typeof(Application.Activities.List.Handler));
            services.AddSignalR();

            services.AddControllersWithViews(opt =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddFluentValidation(config => {
                config.RegisterValidatorsFromAssemblyContaining <Application.Activities.Create>();
            });
            services.AddRazorPages();


            var builder         = services.AddIdentityCore <AppUser>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

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

            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("IsActivityHost", policy =>
                {
                    policy.Requirements.Add(new IsHostRequirement());
                });
            });
            services.AddTransient <IAuthorizationHandler, IsHostRequirementHandler>();

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

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero     // don't allow wiggle room on expiry
                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path        = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chat")))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IUserAccessor, UserAccessor>();
            services.AddScoped <IPhotoAccessor, PhotoAccessor>();
            services.AddScoped <IProfileReader, ProfileReader>();

            services.Configure <CloudinarySettings>(Configuration.GetSection("Cloudinary"));
        }
示例#18
0
 /// <summary>
 /// Adds a Dapper implementation of ASP.NET Core Identity stores.
 /// </summary>
 /// <param name="builder">Helper functions for configuring identity services.</param>
 /// <param name="configureAction">Delegate for configuring options </param>
 /// <returns>The <see cref="IdentityBuilder"/> instance this method extends.</returns>
 public static IdentityBuilder AddDapperStores(this IdentityBuilder builder, Action <DapperStoreOptions> configureAction = null)
 {
     AddStores(builder.Services, builder.UserType, builder.RoleType, configureAction);
     return(builder);
 }
示例#19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <CapstoneEntities>();

            #region DI

            services.AddScoped <IDbFactory, DbFactory>();
            services.AddTransient <IUnitOfWork, UnitOfWork>();

            //WorkFlow
            services.AddTransient <IWorkFlowRepository, WorkFlowRepository>();
            services.AddTransient <IWorkFlowService, WorkFlowService>();

            //ActionType
            services.AddTransient <IActionTypeRepository, ActionTypeRepository>();
            services.AddTransient <IActionTypeService, ActionTypeService>();

            //Group
            services.AddTransient <IGroupRepository, GroupRepository>();
            services.AddTransient <IGroupService, GroupService>();

            //UserGroup
            services.AddTransient <IUserGroupRepository, UserGroupRepository>();
            services.AddTransient <IUserGroupService, UserGroupService>();

            //Role
            services.AddTransient <IRoleRepository, RoleRepository>();
            services.AddTransient <IRoleService, RoleService>();

            //RoleOfGroup
            services.AddTransient <IRoleOfGroupRepository, RoleOfGroupRepository>();
            services.AddTransient <IRoleOfGroupService, RoleOfGroupService>();

            //Permission
            services.AddTransient <IPermissionRepository, PermissionRepository>();
            services.AddTransient <IPermissionService, PermissionService>();

            //PermissionOfRole
            services.AddTransient <IPermissionOfRoleRepository, PermissionOfRoleRepository>();
            services.AddTransient <IPermissionOfRoleService, PermissionOfRoleService>();

            //UserRole
            services.AddTransient <IUserRoleRepository, UserRoleRepository>();
            services.AddTransient <IUserRoleService, UserRoleService>();

            //Notification
            services.AddTransient <INotificationRepository, NotificationRepository>();
            services.AddTransient <INotificationService, NotificationService>();

            //UserNotification
            services.AddTransient <IUserNotificationRepository, UserNotificationRepository>();
            services.AddTransient <IUserNotificationService, UserNotificationService>();

            //User
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IUserService, UserService>();

            //Request
            services.AddTransient <IRequestRepository, RequestRepository>();
            services.AddTransient <IRequestService, RequestService>();

            //RequestAction
            services.AddTransient <IRequestActionRepository, RequestActionRepository>();
            services.AddTransient <IRequestActionService, RequestActionService>();

            //RequestValue
            services.AddTransient <IRequestValueRepository, RequestValueRepository>();
            services.AddTransient <IRequestValueService, RequestValueService>();

            //RequestFile
            services.AddTransient <IRequestFileRepository, RequestFileRepository>();
            services.AddTransient <IRequestFileService, RequestFileService>();

            //Email
            services.AddTransient <IEmailService, EmailServicce>();
            #endregion

            // Auto Mapper Configurations
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });
            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);

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

            // Add identity
            var authBuilder = services.AddIdentityCore <User>(o =>
            {
                // Configure identity options
                o.Password.RequireDigit           = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 6;
            });
            authBuilder = new IdentityBuilder(authBuilder.UserType, typeof(IdentityRole), authBuilder.Services);
            authBuilder.AddEntityFrameworkStores <CapstoneEntities>().AddDefaultTokenProviders();

            //services.AddDbContext<CapstoneEntities>(opt => opt.UseSqlServer("CapstoneEntities"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Capstone API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer",
                                        new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Please enter into field the word 'Bearer' following by space and JWT",
                    Name        = "Authorization",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });
        }
 public AbpIdentityBuilder(IdentityBuilder identityBuilder, Type tenantType)
     : base(identityBuilder.UserType, identityBuilder.RoleType, identityBuilder.Services)
 {
     TenantType = tenantType;
 }
        private static void addBearerSignInManagerOptions(IdentityBuilder identityBuilder, Action <BearerSignInManagerOptions>?configureOptions = null)
        {
            var services = identityBuilder.Services;

            // Both are used by underlying services.
            services.AddLogging();
            services.AddOptions();

            if (configureOptions != null)
            {
                services.Configure(configureOptions);
            }

            services.PostConfigure <BearerSignInManagerOptions>(options => {
                options.CreateDefaultedTokenDescriptor ??= () => new BearerTokenDescriptor(null);
                BearerTokenDescriptor defaultTokenDescriptor = options.CreateDefaultedTokenDescriptor() ?? new BearerTokenDescriptor(null);

                // Only those values are taken over whose property values are null.
                void TakeOverFromDefaultOptions(SecurityTokenDescriptor tokenDescriptor)
                {
                    // Claims can be null..
                    if (tokenDescriptor.Claims.IsNullOrEmpty() && defaultTokenDescriptor.Claims.IsNullOrEmpty())
                    {
                        tokenDescriptor.Claims = new Dictionary <string, object>();
                    }
                    // Take over claims.
                    else if (tokenDescriptor.Claims.IsNullOrEmpty() && !defaultTokenDescriptor.Claims.IsNullOrEmpty())
                    {
                        tokenDescriptor.Claims = new Dictionary <string, object>(defaultTokenDescriptor.Claims);
                    }
                    // Add defaulted claims to existing claims.
                    else if (!tokenDescriptor.Claims.IsNullOrEmpty() && !defaultTokenDescriptor.Claims.IsNullOrEmpty())
                    {
                        foreach (var claim in (ICollection <KeyValuePair <string, object> >)defaultTokenDescriptor.Claims)
                        {
                            tokenDescriptor.Claims.Add(claim);
                        }
                    }

                    tokenDescriptor.Issuer ??= defaultTokenDescriptor.Issuer;
                    tokenDescriptor.Audience ??= defaultTokenDescriptor.Audience;
                    tokenDescriptor.Subject ??= defaultTokenDescriptor.Subject;
                    tokenDescriptor.NotBefore ??= defaultTokenDescriptor.NotBefore;
                    tokenDescriptor.IssuedAt ??= defaultTokenDescriptor.IssuedAt;
                    tokenDescriptor.SigningCredentials ??= defaultTokenDescriptor.SigningCredentials;
                }

                var createAccessTokenDescriptor = options.CreateAccessTokenDescriptor ??=
                                                  () => new BearerTokenDescriptor(null);

                options.CreateAccessTokenDescriptor = () => {
                    var tokenDescriptor = createAccessTokenDescriptor();
                    tokenDescriptor.Expires ??= defaultTokenDescriptor.Expires ?? DateTime.UtcNow.AddMinutes(15);
                    TakeOverFromDefaultOptions(tokenDescriptor);
                    return(tokenDescriptor);
                };

                var createRefreshTokenDescriptor = options.CreateRefreshTokenDescriptor ??=
                                                   () => new BearerTokenDescriptor(null);

                options.CreateRefreshTokenDescriptor = () => {
                    var tokenDescriptor = createRefreshTokenDescriptor();
                    tokenDescriptor.Expires ??= defaultTokenDescriptor.Expires ?? DateTime.UtcNow.AddDays(7);
                    TakeOverFromDefaultOptions(tokenDescriptor);
                    return(tokenDescriptor);
                };
            });
        }
示例#22
0
 public static IdentityBuilder AddCassandraErrorDescriber <TErrorDescriber>(
     this IdentityBuilder builder) where TErrorDescriber : CassandraErrorDescriber
 {
     builder.Services.AddScoped <CassandraErrorDescriber, TErrorDescriber>();
     return(builder);
 }
        public static IdentityBuilder AddBearerSignInManager <DbContextType, UserType, RoleType>(this IdentityBuilder identityBuilder, Func <IServiceProvider, IBearerSignInManager> bearerSignInManagerFactory,
                                                                                                 Action <BearerSignInManagerOptions>?configureOptions = null)
            where DbContextType : DbContext
            where UserType : class
            where RoleType : class
        {
            addBearerSignInManagerOptions(identityBuilder, configureOptions);
            var services = identityBuilder.Services;

            services.AddScoped(bearerSignInManagerFactory);
            return(identityBuilder);
        }
示例#24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CrApiDetails>(Configuration.GetSection("CrApiDetails"));

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

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

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

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Szuper admin", policy => { policy.RequireRole("Szuper admin"); });
                options.AddPolicy("Admin", policy => { policy.RequireRole("Admin"); });
                options.AddPolicy("Fejlesztő", policy => { policy.RequireRole("Fejlesztő"); });
            });

            services.AddDbContext <ApplicationDbContext>(options =>
            {
                options.UseLazyLoadingProxies();
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            }, ServiceLifetime.Transient);

            // Inject repositories
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IRoleRepository, RoleRepository>();
            services.AddTransient <ICRAccountRepository, CRAccountRepository>();
            services.AddTransient <IAnnouncementRepository, AnnouncementRepository>();
            services.AddTransient <IPostRepository, PostRepository>();
            services.AddTransient <IFollowRepository, FollowRepository>();

            // Inject services
            services.AddTransient <IUserService, UserService>();
            services.AddTransient <IRoleService, RoleService>();
            services.AddTransient <ICRAccountService, CRAccountService>();
            services.AddTransient <IAnnouncementService, AnnouncementService>();
            services.AddTransient <IPostService, PostService>();
            services.AddTransient <IGameDataService, GameDataService>();
            services.AddTransient <IFollowService, FollowService>();

            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();

                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });
            services.AddCors();
            services.AddAutoMapper(typeof(UserRepository).Assembly);
            services.AddAutoMapper(typeof(PostRepository).Assembly);
            services.AddScoped <LogUserActivity>();

            services.AddResponseCompression(options => { options.Providers.Add <GzipCompressionProvider>(); });

            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Optimal;
            });
        }
示例#25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(config => config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver())
            .AddJsonOptions(config => config.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            services.AddTransient <ITorrentService, TorrentService>();
            services.AddTransient <IDiagnosticsService, DiagnosticsService.Services.DiagnosticsService>();
            services.AddTransient <IJwtFactory, JwtFactory>();
            services.AddTransient <IStorageService, StorageService>();
            services.AddTransient <ISSHClient, SSHClient>();

            services.AddDbContext <AuthenticationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Networktools")));

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MapProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));


            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(KeyFactory.GetKey(), SecurityAlgorithms.HmacSha256);
            });

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,
                ValidIssuer    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = false,
                ValidAudience    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = KeyFactory.GetKey(),

                RequireExpirationTime = false,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;
            });

            // api user claim policy
            services.AddAuthorization();

            var builder = services.AddIdentityCore <User>(o =>
            {
                // configure identity options
                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(Role), builder.Services);
            builder.AddEntityFrameworkStores <Authentication.DataAccess.AuthenticationDbContext>().AddDefaultTokenProviders();

            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
示例#26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <PhotoSettings>(Configuration.GetSection("PhotoSettings"));

            services.AddScoped <IVehicleRepository, VehicleRepository>();
            services.AddScoped <IPhotoRepository, PhotoRepository>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();

            services.AddAutoMapper();

            services.AddDbContext <VegaDbContext>(options =>
                                                  options.UseSqlServer(Configuration.GetConnectionString("Default")));

            services.AddSingleton <IJwtFactory, JwtFactory>();

            // jwt wire up
            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration["JwtIssuerOptions:Key"])),
                    SecurityAlgorithms.HmacSha256);
            });

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration["JwtIssuerOptions:Key"])),

                RequireExpirationTime = false,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;
            });

            // api user claim policy
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
            });

            // api user claim policy
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
            });

            // add identity
            var builder = services.AddIdentityCore <ApplicationUser>(o =>
            {
                // configure identity options
                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(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores <VegaDbContext>().AddDefaultTokenProviders();


            services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>());;

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
示例#27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // Configuração para conexão com o banco de dados
            services.AddDbContext <Contexto>(
                x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))
                );

            // Registra o gerador Swagger, definindo 1 ou mais documentos Swagger
            services.AddSwaggerGen(c =>
            {
                // Para fins de documentação
                c.SwaggerDoc(
                    "v1",
                    new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "ToDo API",
                    Description    = "A simple example ASP.NET Core Web API",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact        = new OpenApiContact
                    {
                        Name  = "Shayne Boyer",
                        Email = string.Empty,
                        Url   = new Uri("https://twitter.com/spboyer"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url  = new Uri("https://example.com/license"),
                    }
                }
                    );

                c.AddSecurityDefinition(
                    "Bearer",
                    new OpenApiSecurityScheme
                {
                    In          = ParameterLocation.Header,
                    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",
                    Type        = SecuritySchemeType.ApiKey
                }
                    );

                c.AddSecurityRequirement(
                    new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                }
                    );
            });

            // Configuração para usar o Identity
            // options.Password configura a criação da senha
            IdentityBuilder builder = services.AddIdentityCore <User>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
            });

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

            // Configuração para autenticação e autorização
            var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            // Configuração para solicitar autorização nas rotas
            var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();

            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthorizeFilter(policy));
            });

            // Configuração para evitar erro de "possível ciclo de objeto que não é compatíve"
            services.AddControllers().AddNewtonsoftJson(options =>
                                                        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                                        );

            // Implementação de Interfaces e Repositories
            services.AddScoped <IUsuario, UsuarioRepository>();

            // Mapper para Models e DTOs
            services.AddAutoMapper(typeof(MapperProfiles));

            // Configuração de permissão Cors
            services.AddCors();
        }
示例#28
0
        public void ConfigureServices(IServiceCollection services)
        {
            // AddIdentity uses defaults; AddIdentityCore allows customisation
            IdentityBuilder builder = services.AddIdentityCore <User>(opt =>
            {
                // Not for prod!
                opt.Password.RequireDigit           = false;
                opt.Password.RequiredLength         = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
            });

            // Set up main identity framework
            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <DataContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();

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

            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
                options.AddPolicy("ModeratePhotoRole", policy => policy.RequireRole("Admin", "Moderator"));
                options.AddPolicy("VipOnly", policy => policy.RequireRole("VIP"));
            });

            services.AddControllers(options => {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();

                options.Filters.Add(new AuthorizeFilter(policy));
            });

            // Use NewtonSoft JSON
            services.AddControllers().AddNewtonsoftJson(opt => {
                // Don't worry about self-referencing errors
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            services.AddCors();

            // Load config into a class
            services.Configure <CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));

            // Resolve with any class in our assembly
            services.AddAutoMapper(typeof(DatingRepository).Assembly);

            services.AddTransient <Seed>();
            services.AddScoped <IDatingRepository, DatingRepository>();
            services.AddScoped <LogUserActivity>();

            // services.AddScoped<IAuthRepository, AuthRepository>();
        }
示例#29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // jwt wire up
            services.AddSingleton <IJwtFactory, JwtFactory>();

            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = _signingKey,

                RequireExpirationTime = false,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero,
            };

            services.AddAuthentication(options =>
            {
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;
            });

            var builder = new SqlConnectionStringBuilder(
                Configuration.GetConnectionString("ApplicationDB"));

            builder.Password = Configuration.GetSection("ApplicationDB")["DbPassword"];

            //TODO: Add seperate connection string for this context
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             builder.ConnectionString
                                                             )
                                                         );

            // api user claim policy
            services.AddAuthorization(options =>
            {
                options.AddPolicy("BotAdmin", policy => {
                    policy.RequireAuthenticatedUser();
                    policy.RequireClaim(ClaimTypes.Role);
                    policy.RequireRole("BotAdmin");
                    policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
                });
            });

            services.AddDefaultIdentity <ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>().AddDefaultTokenProviders();

            var identityBuilder = services.AddIdentityCore <ApplicationUser>(o =>
            {
                // configure identity options
                o.Password.RequireDigit           = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 6;
            });

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

            services.AddControllersWithViews();
            services.AddRazorPages();

            var logConfig = new LoggerConfiguration().ReadFrom.Configuration(Configuration);
            var logger    = logConfig.CreateLogger();

            services.AddSingleton <Serilog.ILogger>(logger);

            //services.AddTransient<IEmailSender, EmailSender>();
            services.AddTransient <IWikiAccessLogic, WikiAccessLogic>();
            services.AddTransient <IWikiJobRetriever, TFWikiJobRetriever>();
            services.AddTransient <IDataAccess, SqlDataAccess>();

            services.AddSwaggerGen(options =>
            {
                options.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
                {
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "Bearer",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Name         = "Authorization",

                    //Flows = new OpenApiOAuthFlows
                    //{
                    //    Implicit = new OpenApiOAuthFlow
                    //    {
                    //        //AuthorizationUrl = new Uri("https://localhost:5001/api/authenticationcontroller/login"),
                    //        TokenUrl = new Uri("https://localhost:5001/api/authenticationcontroller/login"),
                    //        Scopes = new Dictionary<string, string>
                    //        {
                    //            {"api1", "Demo API - full access"}
                    //        }
                    //    }
                    //}
                });

                options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "ApiKey"
                            },
                        },
                        new List <string>()
                    }
                });
                options.OperationFilter <AuthorizeCheckOperationFilter>();
            });
            //services.Configure<AuthMessageSenderOptions>(Configuration);

            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.WithOrigins(Configuration.GetValue <string>("AllowedDomains")));
                c.AddPolicy("AllowAllHeaders",
                            builder =>
                {
                    builder.WithOrigins("http://localhost:4200")
                    .AllowAnyHeader();
                });
            });
        }
        public static IdentityBuilder AddCloudscribeIdentity(
            this IServiceCollection services,
            Action<IdentityOptions> setupAction = null
            )
        {
            services.AddSingleton<IOptions<IdentityOptions>, SiteIdentityOptionsResolver>();

            
            // Services used by identity

            services.TryAddScoped<IUserClaimsPrincipalFactory<SiteUser>, SiteUserClaimsPrincipalFactory<SiteUser, SiteRole>>();
            services.TryAddScoped<IPasswordHasher<SiteUser>, SitePasswordHasher<SiteUser>>();
            services.TryAddScoped<SiteSignInManager<SiteUser>, SiteSignInManager<SiteUser>>();
            services.TryAddSingleton<SiteAuthCookieValidator, SiteAuthCookieValidator>();
            services.TryAddScoped<SiteCookieAuthenticationEvents, SiteCookieAuthenticationEvents>();
            services.AddSingleton<IAntiforgeryTokenStore, SiteAntiforgeryTokenStore>();

            services.AddAuthentication(options =>
            {
                // This is the Default value for ExternalCookieAuthenticationScheme
                options.SignInScheme = new IdentityCookieOptions().ExternalCookieAuthenticationScheme;
            });

            // Hosting doesn't add IHttpContextAccessor by default
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            // Identity services
            services.TryAddSingleton<IdentityMarkerService>();
            services.TryAddScoped<IUserValidator<SiteUser>, UserValidator<SiteUser>>();
            services.TryAddScoped<IPasswordValidator<SiteUser>, PasswordValidator<SiteUser>>();
            //services.TryAddScoped<IPasswordHasher<SiteUser>, PasswordHasher<SiteUser>>();
            services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
            services.TryAddScoped<IRoleValidator<SiteRole>, RoleValidator<SiteRole>>();
            // No interface for the error describer so we can add errors without rev'ing the interface
            services.TryAddScoped<IdentityErrorDescriber>();
            services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<SiteUser>>();
            //services.TryAddScoped<IUserClaimsPrincipalFactory<SiteUser>, UserClaimsPrincipalFactory<SiteUser, SiteRole>>();
            //services.TryAddScoped<UserManager<SiteUser>, UserManager<SiteUser>>();
            //services.TryAddScoped<SignInManager<SiteUser>, SignInManager<SiteUser>>();
            //services.TryAddScoped<RoleManager<SiteRole>, RoleManager<SiteRole>>();

            services.TryAddScoped<ICustomClaimProvider, DoNothingCustomClaimProvider>();

            if (setupAction != null)
            {
                services.Configure(setupAction);
            }

            var builder = new IdentityBuilder(typeof(SiteUser), typeof(SiteRole), services);

            builder.AddUserStore<UserStore<SiteUser>>()
             .AddRoleStore<RoleStore<SiteRole>>()
             .AddUserManager<SiteUserManager<SiteUser>>()
             .AddRoleManager<SiteRoleManager<SiteRole>>()
             ;

            var dataProtectionProviderType = typeof(DataProtectorTokenProvider<SiteUser>);
            var phoneNumberProviderType = typeof(PhoneNumberTokenProvider<SiteUser>);
            var emailTokenProviderType = typeof(EmailTokenProvider<SiteUser>);
            services.Configure<TokenOptions>(options =>
            {
                options.ProviderMap[TokenOptions.DefaultProvider] = new TokenProviderDescriptor(dataProtectionProviderType);
                options.ProviderMap[TokenOptions.DefaultEmailProvider] = new TokenProviderDescriptor(emailTokenProviderType);
                options.ProviderMap[TokenOptions.DefaultPhoneProvider] = new TokenProviderDescriptor(phoneNumberProviderType);
            });
            services.TryAddTransient(dataProtectionProviderType);
            services.TryAddTransient(emailTokenProviderType);
            services.TryAddTransient(phoneNumberProviderType);


            services.TryAddScoped<IIdentityServerIntegration, NotIntegratedIdentityServerIntegration>();

            return builder;

            //return services;
        }
示例#31
0
 /// <summary>
 /// Adds an Entity Framework implementation of identity information stores.
 /// </summary>
 /// <param name="builder">The <see cref="IdentityBuilder"/> instance this method extends.</param>
 /// <returns>The <see cref="IdentityBuilder"/> instance this method extends.</returns>
 public static IdentityBuilder AddNHibernateStores(this IdentityBuilder builder)
 {
     builder.Services.TryAdd(GetDefaultServices(builder.UserType, builder.RoleType));
     return(builder);
 }