本文整理汇总了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);
}
示例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();
}
}
示例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();
}
示例4: CreateTestServices
public static IServiceCollection CreateTestServices()
{
var services = new ServiceCollection();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddLogging();
services.AddIdentity<IdentityUser, IdentityRole>();
return services;
}
示例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();
}
示例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);
}
示例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();
}
示例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);
}
示例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);
}
示例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();
}
示例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"));
}