本文整理汇总了C#中IdentityUser类的典型用法代码示例。如果您正苦于以下问题:C# IdentityUser类的具体用法?C# IdentityUser怎么用?C# IdentityUser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
IdentityUser类属于命名空间,在下文中一共展示了IdentityUser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RegisterUser
public async Task<IdentityResult> RegisterUser(UserModel userModel, string roleName)
{
IdentityUser user = new IdentityUser
{
UserName = userModel.UserName,
Email = userModel.UserName
};
var result = await _userManager.CreateAsync(user, userModel.Password);
if (result == IdentityResult.Success)
{
var role = await _roleManager.FindByNameAsync(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
var roleresult = await _roleManager.CreateAsync(role);
}
var userFromDb = await _userManager.FindByNameAsync(user.UserName);
if (userFromDb != null)
{
await _userManager.AddToRoleAsync(userFromDb.Id, roleName);
}
}
return result;
}
示例2: AddRemoveUserClaimTest
public async Task AddRemoveUserClaimTest()
{
var db = UnitTestHelper.CreateDefaultDb();
var store = new UserStore<IdentityUser>(db);
;
var user = new IdentityUser("ClaimsAddRemove");
await store.CreateAsync(user);
Claim[] claims = {new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3")};
foreach (Claim c in claims)
{
await store.AddClaimAsync(user, c);
}
await store.UpdateAsync(user);
var userClaims = await store.GetClaimsAsync(user);
Assert.Equal(3, userClaims.Count);
await store.RemoveClaimAsync(user, claims[0]);
Assert.Equal(3, userClaims.Count); // No effect until save changes
db.SaveChanges();
userClaims = await store.GetClaimsAsync(user);
Assert.Equal(2, userClaims.Count);
await store.RemoveClaimAsync(user, claims[1]);
Assert.Equal(2, userClaims.Count); // No effect until save changes
db.SaveChanges();
userClaims = await store.GetClaimsAsync(user);
Assert.Equal(1, userClaims.Count);
await store.RemoveClaimAsync(user, claims[2]);
Assert.Equal(1, userClaims.Count); // No effect until save changes
db.SaveChanges();
userClaims = await store.GetClaimsAsync(user);
Assert.Equal(0, userClaims.Count);
//Assert.Equal(0, user.Claims.Count);
}
示例3: btnRegister_Click
protected void btnRegister_Click(object sender, EventArgs e)
{
try
{
// Default UserStore constructor uses the default connection string named: DefaultConnection
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = txtUsername.Text };
IdentityResult result = manager.Create(user, txtPassword.Text);
if (result.Succeeded)
{
//lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
//lblStatus.CssClass = "label label-success";
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
Response.Redirect("admin/main-menu.aspx");
}
else
{
lblStatus.Text = result.Errors.FirstOrDefault();
lblStatus.CssClass = "label label-danger";
}
}
catch (Exception q)
{
Response.Redirect("/error.aspx");
}
}
示例4: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
List<string> roles = new List<string>();
IdentityUser user = new IdentityUser();
using (AuthRepository _repo = new AuthRepository())
{
user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "Потребителското име или паролата не са верни.");
return;
}
else
{
roles = await _repo.GetRolesForUser(user.Id);
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
foreach (var item in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, item));
}
context.Validated(identity);
context.Response.Headers.Add("UserRoles", roles.ToArray());
}
示例5: DeleteAsync
public async Task<int> DeleteAsync(IdentityUser user)
{
if (user == null)
throw new ArgumentNullException(nameof(user));
return await DeleteAsync(user.Id);
}
示例6: SetPassword
private static void SetPassword(IdentityUser user, string password, int passwordExpirationInMinutes, DateTime currentDate)
{
user.Password.Hash = password;
user.Password.ExpirationDateUtc = passwordExpirationInMinutes > 0
? currentDate.AddMinutes(passwordExpirationInMinutes)
: default(DateTime?);
}
示例7: EnsureStartupUsageWorks
public async Task EnsureStartupUsageWorks()
{
var context = CreateContext(true);
IBuilder builder = new Builder.Builder(new ServiceCollection().BuildServiceProvider());
builder.UseServices(services =>
{
services.AddEntityFramework().AddSqlServer();
services.AddIdentitySqlServer();
services.SetupOptions<DbContextOptions>(options =>
options.UseSqlServer(ConnectionString));
// todo: constructor resolution doesn't work well with IdentityDbContext since it has 4 constructors
services.AddInstance(context);
});
var userStore = builder.ApplicationServices.GetService<IUserStore<IdentityUser>>();
var userManager = builder.ApplicationServices.GetService<UserManager<IdentityUser>>();
Assert.NotNull(userStore);
Assert.NotNull(userManager);
const string userName = "admin";
const string password = "[email protected]";
var user = new IdentityUser { UserName = userName };
IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
IdentityResultAssert.IsSuccess(await userManager.DeleteAsync(user));
}
示例8: CanIncludeUserClaimsTest
public async Task CanIncludeUserClaimsTest()
{
// Arrange
CreateContext(true);
var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
var services = new ServiceCollection();
DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
builder.ApplicationServices = services.BuildServiceProvider();
var userManager = builder.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>();
var dbContext = builder.ApplicationServices.GetRequiredService<IdentityDbContext>();
var username = "user" + new Random().Next();
var user = new IdentityUser() { UserName = username };
IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user));
for (var i = 0; i < 10; i++)
{
IdentityResultAssert.IsSuccess(await userManager.AddClaimAsync(user, new Claim(i.ToString(), "foo")));
}
user = dbContext.Users.Include(x => x.Claims).FirstOrDefault(x => x.UserName == username);
// Assert
Assert.NotNull(user);
Assert.NotNull(user.Claims);
Assert.Equal(10, user.Claims.Count());
}
示例9: AddLogin
public void AddLogin(IdentityUser user, UserLoginInfo login)
{
_db[_tables.UsersLogins].Insert(
LoginProvider: login.LoginProvider,
ProviderKey: login.ProviderKey,
UserId: user.Id);
}
示例10: UserWithLogin
public static IdentityUser UserWithLogin()
{
var user = new IdentityUser();
user.AddLogin(new UserLoginInfo("test", "testing"));
return user;
}
示例11: UserWithTestRole
public static IdentityUser UserWithTestRole()
{
var user = new IdentityUser();
user.AddRole("test");
return user;
}
示例12: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (MyUserManager userManager = new MyUserManager())
{
IdentityUser user = new IdentityUser();
if (FindUser(context.UserName, context.Password) != null)
{
user = userManager.FindByName(context.UserName);
}
//IdentityUser user2 = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
示例13: RegisterCustomerAsync
public async Task<IdentityResult> RegisterCustomerAsync(UserModel userModel, AppRole appRole = AppRole.customer)
{
var addToRoleResult = new IdentityResult();
// Add generate username to the model
IdentityUser user = new IdentityUser
{
UserName = userModel.UserName,
Email = userModel.EmailAddress,
EmailConfirmed = true,
PhoneNumber = userModel.PhoneNumber,
PhoneNumberConfirmed = true,
};
var result = await _userManager.CreateAsync(user, userModel.Password);
//Role-user combination is managed as Contact-Role combination in ContactRole table
//Create Role Admin if it does not exist
var _role = await _roleManager.FindByNameAsync(appRole.ToString());
if (_role == null)
{
_role = new IdentityRole(appRole.ToString());
var roleresult = await _roleManager.CreateAsync(_role);
}
var rolesForUser = await _userManager.GetRolesAsync(user.Id);
if (!rolesForUser.Contains(_role.Name))
{
addToRoleResult = await _userManager.AddToRoleAsync(user.Id, _role.Name);
}
return addToRoleResult;
}
示例14: OnValidateIdentityRejectsWhenValidateSecurityStampFails
public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails()
{
var user = new IdentityUser("test");
var httpContext = new Mock<HttpContext>();
var userManager = MockHelpers.MockUserManager<IdentityUser>();
var authManager = new Mock<IAuthenticationManager>();
var claimsManager = new Mock<IClaimsIdentityFactory<IdentityUser>>();
var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object,
authManager.Object, claimsManager.Object);
signInManager.Setup(s => s.ValidateSecurityStamp(It.IsAny<ClaimsIdentity>(), user.Id)).ReturnsAsync(null).Verifiable();
var services = new ServiceCollection();
services.AddInstance(signInManager.Object);
httpContext.Setup(c => c.ApplicationServices).Returns(services.BuildServiceProvider());
var id = new ClaimsIdentity(ClaimsIdentityOptions.DefaultAuthenticationType);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow });
var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
Assert.NotNull(context.Properties);
Assert.NotNull(context.Options);
Assert.NotNull(context.Identity);
await
SecurityStampValidator.OnValidateIdentity<IdentityUser>(TimeSpan.Zero).Invoke(context);
Assert.Null(context.Identity);
signInManager.VerifyAll();
}
示例15: Dont_add_duplicate_no_named_users
public void Dont_add_duplicate_no_named_users()
{
var newUser = new IdentityUser();
CreateUser(newUser);
var nextUser = new IdentityUser();
CreateUser(nextUser);
}