本文整理汇总了C#中IdentityUser类的典型用法代码示例。如果您正苦于以下问题:C# IdentityUser类的具体用法?C# IdentityUser怎么用?C# IdentityUser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
IdentityUser类属于命名空间,在下文中一共展示了IdentityUser类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
}
开发者ID:lachezar1990,项目名称:test8,代码行数:29,代码来源:AuthRepository.cs
示例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);
}
开发者ID:tomi85,项目名称:aspnetidentity,代码行数:32,代码来源:UserClaimsTest.cs
示例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");
}
}
开发者ID:JamesIsNinja,项目名称:comp2007lab4,代码行数:32,代码来源:register.aspx.cs
示例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());
}
开发者ID:lachezar1990,项目名称:test8,代码行数:33,代码来源:SimpleAuthorizationServerProvider.cs
示例5: DeleteAsync
public async Task<int> DeleteAsync(IdentityUser user)
{
if (user == null)
throw new ArgumentNullException(nameof(user));
return await DeleteAsync(user.Id);
}
开发者ID:saitolabs,项目名称:AspNet-IdSrv-Identity-Oracle-Dapper,代码行数:7,代码来源:UserRepository.cs
示例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?);
}
开发者ID:Lampart071,项目名称:DHub.CQRS,代码行数:7,代码来源:UserFactory.cs
示例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));
}
开发者ID:ChMar,项目名称:Identity,代码行数:27,代码来源:DefaultPocoTest.cs
示例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());
}
开发者ID:stormwild,项目名称:Identity,代码行数:30,代码来源:DefaultPocoTest.cs
示例9: AddLogin
public void AddLogin(IdentityUser user, UserLoginInfo login)
{
_db[_tables.UsersLogins].Insert(
LoginProvider: login.LoginProvider,
ProviderKey: login.ProviderKey,
UserId: user.Id);
}
开发者ID:rioka,项目名称:Simple.Data.AspNet.Identity,代码行数:7,代码来源:UserLoginsTable.cs
示例10: UserWithLogin
public static IdentityUser UserWithLogin()
{
var user = new IdentityUser();
user.AddLogin(new UserLoginInfo("test", "testing"));
return user;
}
开发者ID:rzakirov,项目名称:MongoIdentity,代码行数:7,代码来源:IdentityUserMother.cs
示例11: UserWithTestRole
public static IdentityUser UserWithTestRole()
{
var user = new IdentityUser();
user.AddRole("test");
return user;
}
开发者ID:rzakirov,项目名称:MongoIdentity,代码行数:7,代码来源:IdentityUserMother.cs
示例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);
}
}
开发者ID:bandiandras,项目名称:SzoftverProjekt,代码行数:27,代码来源:ApplicationOAuthProvider.cs
示例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;
}
开发者ID:itssourabh22,项目名称:projectIGI,代码行数:31,代码来源:AuthRepository.cs
示例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();
}
开发者ID:ChMar,项目名称:Identity,代码行数:26,代码来源:SecurityStampValidatorTest.cs
示例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);
}
开发者ID:JamesWhiteAtx,项目名称:Asp.Identity.Oracle,代码行数:7,代码来源:EndToEndTests.cs
示例16: RemoveLogin
public void RemoveLogin(IdentityUser user, UserLoginInfo login)
{
_db[_tables.UsersLogins].Delete(
UserId: user.Id,
LoginProvider: login.LoginProvider,
ProviderKey: login.ProviderKey);
}
开发者ID:rioka,项目名称:Simple.Data.AspNet.Identity,代码行数:7,代码来源:UserLoginsTable.cs
示例17: CreateUser_Click
protected void CreateUser_Click(object sender, EventArgs e)
{
// Default UserStore constructor uses the default connection string named: DefaultConnectionEF
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = txtUName.Text };
user.Email = txtEmail.Text;
user.PhoneNumber = txtPhone.Text;
IdentityResult result = manager.Create(user, txtPass.Text);
if (result.Succeeded)
{
lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
Response.Redirect("/admin/main.aspx");
}
else
{
lblStatus.Text = result.Errors.FirstOrDefault();
}
}
开发者ID:irichardi,项目名称:assign2,代码行数:25,代码来源:register.aspx.cs
示例18: Create
public async Task<HttpResponseMessage> Create()
{
HttpResponseMessage response;
try
{
var usuario = new IdentityUser
{
UserName = "ffonseca"
};
var userManager = Request.GetOwinContext().GetUserManager<AppUserManager>();
IdentityResult result = await userManager.CreateAsync(usuario, "[email protected]@");
string resultado;
if (result.Succeeded)
{
resultado = "Usuario Criado com sucesso";
}
else
{
resultado = string.Join(",", result.Errors);
}
response = Request.CreateResponse(HttpStatusCode.OK, resultado);
}
catch (Exception ex)
{
response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
return await Task.FromResult(response);
}
开发者ID:gsonego,项目名称:DevMediaDemo,代码行数:35,代码来源:AccountController.cs
示例19: IdentityMapperAppUserRelationsAreMapped
public void IdentityMapperAppUserRelationsAreMapped()
{
IdentityUser dbUser = new IdentityUser
{
Logins =
new List<IdentityUserLogin>
{
new IdentityUserLogin(),
new IdentityUserLogin(),
new IdentityUserLogin()
},
Roles = new List<IdentityUserRole>
{
new IdentityUserRole(),
new IdentityUserRole()
},
Claims = new List<IdentityUserClaim>
{
new IdentityUserClaim()
}
};
ApplicationUser result = IdentityMapper.MapAppUserFromDbUser(dbUser);
result.Should().NotBeNull();
result.Logins.Should().NotBeNull();
result.Logins.Count.Should().Be(3);
result.Roles.Should().NotBeNull();
result.Roles.Count.Should().Be(2);
result.Claims.Should().NotBeNull();
result.Claims.Count.Should().Be(1);
}
开发者ID:targitaj,项目名称:m3utonetpaleyerxml,代码行数:31,代码来源:IdentityMapperTests.cs
示例20: InsertUser
public void InsertUser(IdentityUser user)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
var i = _database.As<IUserRepository>();
_database.Execute("InsertUser", new
{
email = user.Email,
emailConfirmed = user.EmailConfirmed,
passwordHash = user.PasswordHash,
securityStamp = user.SecurityStamp,
phoneNumber = user.PhoneNumber,
phoneNumberConfirmed = user.PhoneNumberConfirmed,
twoFactorEnabled = user.TwoFactorEnabled,
lockoutEndDate = user.LockoutEndDate,
lockoutEnabled = user.LockoutEnabled,
accessFailedCount = user.AccessFailedCount,
id = user.Id,
userName = user.UserName
});
i.InsertUser(user);
}
开发者ID:JCasterline,项目名称:AspNet.Identity.Insight,代码行数:26,代码来源:UserRepository.cs
注:本文中的IdentityUser类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论