当前位置: 首页>>代码示例>>C#>>正文


C# ServiceCollection.AddIdentity方法代码示例

本文整理汇总了C#中ServiceCollection.AddIdentity方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.AddIdentity方法的具体用法?C# ServiceCollection.AddIdentity怎么用?C# ServiceCollection.AddIdentity使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ServiceCollection的用法示例。


在下文中一共展示了ServiceCollection.AddIdentity方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: IdentityOptionsFromConfig

        public void IdentityOptionsFromConfig()
        {
            const string roleClaimType = "rolez";
            const string usernameClaimType = "namez";
            const string useridClaimType = "idz";
            const string securityStampClaimType = "stampz";

            var dic = new Dictionary<string, string>
            {
                {"identity:claimsidentity:roleclaimtype", roleClaimType},
                {"identity:claimsidentity:usernameclaimtype", usernameClaimType},
                {"identity:claimsidentity:useridclaimtype", useridClaimType},
                {"identity:claimsidentity:securitystampclaimtype", securityStampClaimType},
                {"identity:user:requireUniqueEmail", "true"},
                {"identity:password:RequiredLength", "10"},
                {"identity:password:RequireNonAlphanumeric", "false"},
                {"identity:password:RequireUpperCase", "false"},
                {"identity:password:RequireDigit", "false"},
                {"identity:password:RequireLowerCase", "false"},
                {"identity:lockout:AllowedForNewUsers", "FALSe"},
                {"identity:lockout:MaxFailedAccessAttempts", "1000"}
            };
            var builder = new ConfigurationBuilder();
            builder.AddInMemoryCollection(dic);
            var config = builder.Build();
            Assert.Equal(roleClaimType, config["identity:claimsidentity:roleclaimtype"]);

            var services = new ServiceCollection();
            services.AddIdentity<TestUser,TestRole>();
            services.Configure<IdentityOptions>(config.GetSection("identity"));
            var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>();
            Assert.NotNull(accessor);
            var options = accessor.Value;
            Assert.Equal(roleClaimType, options.ClaimsIdentity.RoleClaimType);
            Assert.Equal(useridClaimType, options.ClaimsIdentity.UserIdClaimType);
            Assert.Equal(usernameClaimType, options.ClaimsIdentity.UserNameClaimType);
            Assert.Equal(securityStampClaimType, options.ClaimsIdentity.SecurityStampClaimType);
            Assert.True(options.User.RequireUniqueEmail);
            Assert.Equal("ab[email protected]+", options.User.AllowedUserNameCharacters);
            Assert.False(options.Password.RequireDigit);
            Assert.False(options.Password.RequireLowercase);
            Assert.False(options.Password.RequireNonAlphanumeric);
            Assert.False(options.Password.RequireUppercase);
            Assert.Equal(10, options.Password.RequiredLength);
            Assert.False(options.Lockout.AllowedForNewUsers);
            Assert.Equal(1000, options.Lockout.MaxFailedAccessAttempts);
        }
开发者ID:yuyunyan,项目名称:Identity,代码行数:47,代码来源:IdentityOptionsTest.cs

示例2: TestBase

    public TestBase()
    {
      if (ServiceProvider == null)
      {
        var services = new ServiceCollection();

        // set up empty in-memory test db
        services
          .AddEntityFrameworkInMemoryDatabase()
          .AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));

        // add identity service
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<AllReadyContext>();
        var context = new DefaultHttpContext();
        context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
        services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });

        // Setup hosting environment
        IHostingEnvironment hostingEnvironment = new HostingEnvironment();
        hostingEnvironment.EnvironmentName = "Development";
        services.AddSingleton(x => hostingEnvironment);

        // set up service provider for tests
        ServiceProvider = services.BuildServiceProvider();
      }
    }
开发者ID:gftrader,项目名称:allReady,代码行数:27,代码来源:TestBase.cs

示例3: ManageControllerTest

        public ManageControllerTest()
        {
            var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();

            var services = new ServiceCollection();
            services.AddOptions();
            services
                .AddDbContext<MusicStoreContext>(b => b.UseInMemoryDatabase().UseInternalServiceProvider(efServiceProvider));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<MusicStoreContext>();

            services.AddLogging();
            services.AddOptions();

            // IHttpContextAccessor is required for SignInManager, and UserManager
            var context = new DefaultHttpContext();
            context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature() { Handler = new TestAuthHandler() });
            services.AddSingleton<IHttpContextAccessor>(
                new HttpContextAccessor()
                    {
                        HttpContext = context,
                    });

            _serviceProvider = services.BuildServiceProvider();
        }
开发者ID:Cream2015,项目名称:MusicStore,代码行数:26,代码来源:ManageControllerTest.cs

示例4: CreateTestServices

 public static IServiceCollection CreateTestServices()
 {
     var services = new ServiceCollection();
     services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
     services.AddLogging();
     services.AddIdentity<IdentityUser, IdentityRole>();
     return services;
 }
开发者ID:yonglehou,项目名称:Identity-1,代码行数:8,代码来源:TestIdentityFactory.cs

示例5: ConfigureServices

 private IServiceProvider ConfigureServices()
 {
     var services = new ServiceCollection();
     DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
     services.AddLogging();
     services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
     return services.BuildServiceProvider();
 }
开发者ID:adwardliu,项目名称:Identity,代码行数:8,代码来源:DefaultPocoTest.cs

示例6: CanSetupIdentityOptions

        public void CanSetupIdentityOptions()
        {
            var services = new ServiceCollection();
            services.AddIdentity<TestUser,TestRole>(options => options.User.RequireUniqueEmail = true);
            var serviceProvider = services.BuildServiceProvider();

            var optionsGetter = serviceProvider.GetRequiredService<IOptions<IdentityOptions>>();
            Assert.NotNull(optionsGetter);

            var myOptions = optionsGetter.Value;
            Assert.True(myOptions.User.RequireUniqueEmail);
        }
开发者ID:yuyunyan,项目名称:Identity,代码行数:12,代码来源:IdentityOptionsTest.cs

示例7: GetServiceProvider

		public static IServiceProvider GetServiceProvider()
		{
			var services = new ServiceCollection();
			services.AddMvc();
			services.AddEntityFramework()
				.AddInMemoryDatabase()
				.AddDbContext<ChatLeIdentityDbContext>(options => options.UseInMemoryDatabase());
			services.AddInstance<ILoggerFactory>(new LoggerFactory());
			services.AddIdentity<ChatLeUser, IdentityRole>();
			services.AddChatLe();
			return services.BuildServiceProvider();
		}
开发者ID:IEvangelist,项目名称:chatle,代码行数:12,代码来源:TestUtils.cs

示例8: CanCustomizeIdentityOptions

        public void CanCustomizeIdentityOptions()
        {
            var services = new ServiceCollection()
                .Configure<IdentityOptions>(options => options.Password.RequiredLength = -1);
            services.AddIdentity<TestUser,TestRole>();
            var serviceProvider = services.BuildServiceProvider();

            var setup = serviceProvider.GetRequiredService<IConfigureOptions<IdentityOptions>>();
            Assert.NotNull(setup);
            var optionsGetter = serviceProvider.GetRequiredService<IOptions<IdentityOptions>>();
            Assert.NotNull(optionsGetter);
            var myOptions = optionsGetter.Value;
            Assert.True(myOptions.Password.RequireLowercase);
            Assert.True(myOptions.Password.RequireDigit);
            Assert.True(myOptions.Password.RequireNonAlphanumeric);
            Assert.True(myOptions.Password.RequireUppercase);
            Assert.Equal(-1, myOptions.Password.RequiredLength);
        }
开发者ID:yuyunyan,项目名称:Identity,代码行数:18,代码来源:IdentityOptionsTest.cs

示例9: IdentityOptionsActionOverridesConfig

 public void IdentityOptionsActionOverridesConfig()
 {
     var dic = new Dictionary<string, string>
     {
         {"identity:user:requireUniqueEmail", "true"},
         {"identity:lockout:MaxFailedAccessAttempts", "1000"}
     };
     var builder = new ConfigurationBuilder();
     builder.AddInMemoryCollection(dic);
     var config = builder.Build();
     var services = new ServiceCollection();
     services.Configure<IdentityOptions>(config.GetSection("identity"));
     services.AddIdentity<TestUser, TestRole>(o => { o.User.RequireUniqueEmail = false; o.Lockout.MaxFailedAccessAttempts++; });
     var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>();
     Assert.NotNull(accessor);
     var options = accessor.Value;
     Assert.False(options.User.RequireUniqueEmail);
     Assert.Equal(1001, options.Lockout.MaxFailedAccessAttempts);
 }
开发者ID:yuyunyan,项目名称:Identity,代码行数:19,代码来源:IdentityOptionsTest.cs

示例10: VerifyAccountControllerSignIn

        public async Task VerifyAccountControllerSignIn(bool isPersistent)
        {
            var context = new Mock<HttpContext>();
            var auth = new Mock<AuthenticationManager>();
            context.Setup(c => c.Authentication).Returns(auth.Object).Verifiable();
            auth.Setup(a => a.SignInAsync(new IdentityCookieOptions().ApplicationCookieAuthenticationScheme,
                It.IsAny<ClaimsPrincipal>(),
                It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
            // REVIEW: is persistant mocking broken
            //It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Returns(Task.FromResult(0)).Verifiable();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
            var services = new ServiceCollection();
            services.AddLogging();
            services.AddSingleton(contextAccessor.Object);
            services.AddIdentity<TestUser, TestRole>();
            services.AddSingleton<IUserStore<TestUser>, InMemoryStore<TestUser, TestRole>>();
            services.AddSingleton<IRoleStore<TestRole>, InMemoryStore<TestUser, TestRole>>();
            
            var app = new ApplicationBuilder(services.BuildServiceProvider());
            app.UseCookieAuthentication();

            // Act
            var user = new TestUser
            {
                UserName = "Yolo"
            };
            const string password = "[email protected]!";
            var userManager = app.ApplicationServices.GetRequiredService<UserManager<TestUser>>();
            var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<TestUser>>();

            IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));

            var result = await signInManager.PasswordSignInAsync(user, password, isPersistent, false);

            // Assert
            Assert.True(result.Succeeded);
            context.VerifyAll();
            auth.VerifyAll();
            contextAccessor.VerifyAll();
        }
开发者ID:xuchrist,项目名称:Identity,代码行数:41,代码来源:ControllerTest.cs

示例11: VerifyAccountControllerExternalLoginWithTokensFlow

        public async Task VerifyAccountControllerExternalLoginWithTokensFlow()
        {
            // Setup the external cookie like it would look from a real OAuth2
            var externalId = "<externalId>";
            var authScheme = "<authScheme>";
            var externalIdentity = new ClaimsIdentity();
            externalIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, externalId));
            var externalPrincipal = new ClaimsPrincipal(externalIdentity);
            var externalLogin = new ExternalLoginInfo(externalPrincipal, authScheme, externalId, "displayname")
            {
                AuthenticationTokens = new[] {
                    new AuthenticationToken { Name = "refresh_token", Value = "refresh" },
                    new AuthenticationToken { Name = "access_token", Value = "access" }
                }
            };

            var auth = new Mock<AuthenticationManager>();
            auth.Setup(a => a.AuthenticateAsync(It.IsAny<AuthenticateContext>())).Returns(Task.FromResult(0));
            var context = new Mock<HttpContext>();
            context.Setup(c => c.Authentication).Returns(auth.Object).Verifiable();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
            var services = new ServiceCollection();
            services.AddLogging();
            services.AddSingleton(contextAccessor.Object);
            services.AddIdentity<TestUser, TestRole>();
            services.AddSingleton<IUserStore<TestUser>, InMemoryStore<TestUser, TestRole>>();
            services.AddSingleton<IRoleStore<TestRole>, InMemoryStore<TestUser, TestRole>>();

            var app = new ApplicationBuilder(services.BuildServiceProvider());
            app.UseCookieAuthentication();

            // Act
            var user = new TestUser
            {
                UserName = "Yolo"
            };
            var userManager = app.ApplicationServices.GetRequiredService<UserManager<TestUser>>();
            var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<TestUser>>();

            IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user));
            IdentityResultAssert.IsSuccess(await userManager.AddLoginAsync(user, new UserLoginInfo(authScheme, externalId, "whatever")));
            IdentityResultAssert.IsSuccess(await signInManager.UpdateExternalAuthenticationTokensAsync(externalLogin));
            Assert.Equal("refresh", await userManager.GetAuthenticationTokenAsync(user, authScheme, "refresh_token"));
            Assert.Equal("access", await userManager.GetAuthenticationTokenAsync(user, authScheme, "access_token"));
        }
开发者ID:xuchrist,项目名称:Identity,代码行数:46,代码来源:ControllerTest.cs


注:本文中的ServiceCollection.AddIdentity方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。