Moved POCOs to EF and fixed tests

This commit is contained in:
Suhas Joshi 2015-02-26 11:48:01 -08:00
parent 9e7f12a515
commit 28dc0245bf
37 changed files with 994 additions and 469 deletions

View File

@ -2,6 +2,7 @@
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity.SqlServer; using Microsoft.Data.Entity.SqlServer;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;

View File

@ -2,6 +2,7 @@ using IdentitySample.Models;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics; using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity; using Microsoft.Data.Entity;
using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;

View File

@ -31,6 +31,10 @@ namespace Microsoft.AspNet.Identity.EntityFramework
b.Key(u => u.Id); b.Key(u => u.Id);
b.ForRelational().Table("AspNetUsers"); b.ForRelational().Table("AspNetUsers");
b.Property(u => u.ConcurrencyStamp).ConcurrencyToken(); b.Property(u => u.ConcurrencyStamp).ConcurrencyToken();
b.Collection(u => u.Claims).InverseReference().ForeignKey(uc => uc.UserId);
b.Collection(u => u.Logins).InverseReference().ForeignKey(ul => ul.UserId);
b.Collection(u => u.Roles).InverseReference().ForeignKey(ur => ur.UserId);
}); });
builder.Entity<TRole>(b => builder.Entity<TRole>(b =>
@ -38,19 +42,20 @@ namespace Microsoft.AspNet.Identity.EntityFramework
b.Key(r => r.Id); b.Key(r => r.Id);
b.ForRelational().Table("AspNetRoles"); b.ForRelational().Table("AspNetRoles");
b.Property(r => r.ConcurrencyStamp).ConcurrencyToken(); b.Property(r => r.ConcurrencyStamp).ConcurrencyToken();
b.Collection(r => r.Users).InverseReference().ForeignKey(ur => ur.RoleId);
b.Collection(r => r.Claims).InverseReference().ForeignKey(rc => rc.RoleId);
}); });
builder.Entity<IdentityUserClaim<TKey>>(b => builder.Entity<IdentityUserClaim<TKey>>(b =>
{ {
b.Key(uc => uc.Id); b.Key(uc => uc.Id);
b.Reference<TUser>().InverseCollection().ForeignKey(uc => uc.UserId);
b.ForRelational().Table("AspNetUserClaims"); b.ForRelational().Table("AspNetUserClaims");
}); });
builder.Entity<IdentityRoleClaim<TKey>>(b => builder.Entity<IdentityRoleClaim<TKey>>(b =>
{ {
b.Key(rc => rc.Id); b.Key(rc => rc.Id);
b.Reference<TRole>().InverseCollection().ForeignKey(rc => rc.RoleId);
b.ForRelational().Table("AspNetRoleClaims"); b.ForRelational().Table("AspNetRoleClaims");
}); });
@ -66,7 +71,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework
builder.Entity<IdentityUserLogin<TKey>>(b => builder.Entity<IdentityUserLogin<TKey>>(b =>
{ {
b.Key(l => new { l.LoginProvider, l.ProviderKey }); b.Key(l => new { l.LoginProvider, l.ProviderKey });
b.Reference<TUser>().InverseCollection().ForeignKey(uc => uc.UserId);
b.ForRelational().Table("AspNetUserLogins"); b.ForRelational().Table("AspNetUserLogins");
}); });
} }

View File

@ -4,7 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Microsoft.AspNet.Identity namespace Microsoft.AspNet.Identity.EntityFramework
{ {
/// <summary> /// <summary>
/// Represents a Role entity /// Represents a Role entity
@ -49,12 +49,12 @@ namespace Microsoft.AspNet.Identity
/// <summary> /// <summary>
/// Navigation property for users in the role /// Navigation property for users in the role
/// </summary> /// </summary>
public virtual ICollection<IdentityUserRole<TKey>> Users { get; private set; } = new List<IdentityUserRole<TKey>>(); public virtual ICollection<IdentityUserRole<TKey>> Users { get; } = new List<IdentityUserRole<TKey>>();
/// <summary> /// <summary>
/// Navigation property for claims in the role /// Navigation property for claims in the role
/// </summary> /// </summary>
public virtual ICollection<IdentityRoleClaim<TKey>> Claims { get; private set; } = new List<IdentityRoleClaim<TKey>>(); public virtual ICollection<IdentityRoleClaim<TKey>> Claims { get; } = new List<IdentityRoleClaim<TKey>>();
/// <summary> /// <summary>
/// Role id /// Role id

View File

@ -3,7 +3,7 @@
using System; using System;
namespace Microsoft.AspNet.Identity namespace Microsoft.AspNet.Identity.EntityFramework
{ {
public class IdentityRoleClaim : IdentityRoleClaim<string> { } public class IdentityRoleClaim : IdentityRoleClaim<string> { }

View File

@ -2,8 +2,9 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Collections.Generic;
namespace Microsoft.AspNet.Identity namespace Microsoft.AspNet.Identity.EntityFramework
{ {
public class IdentityUser : IdentityUser<string> public class IdentityUser : IdentityUser<string>
{ {
@ -87,5 +88,20 @@ namespace Microsoft.AspNet.Identity
/// Used to record failures for the purposes of lockout /// Used to record failures for the purposes of lockout
/// </summary> /// </summary>
public virtual int AccessFailedCount { get; set; } public virtual int AccessFailedCount { get; set; }
/// <summary>
/// Navigation property for users in the role
/// </summary>
public virtual ICollection<IdentityUserRole<TKey>> Roles { get; } = new List<IdentityUserRole<TKey>>();
/// <summary>
/// Navigation property for users claims
/// </summary>
public virtual ICollection<IdentityUserClaim<TKey>> Claims { get; } = new List<IdentityUserClaim<TKey>>();
/// <summary>
/// Navigation property for users logins
/// </summary>
public virtual ICollection<IdentityUserLogin<TKey>> Logins { get; } = new List<IdentityUserLogin<TKey>>();
} }
} }

View File

@ -3,7 +3,7 @@
using System; using System;
namespace Microsoft.AspNet.Identity namespace Microsoft.AspNet.Identity.EntityFramework
{ {
public class IdentityUserClaim : IdentityUserClaim<string> { } public class IdentityUserClaim : IdentityUserClaim<string> { }

View File

@ -3,7 +3,7 @@
using System; using System;
namespace Microsoft.AspNet.Identity namespace Microsoft.AspNet.Identity.EntityFramework
{ {
public class IdentityUserLogin : IdentityUserLogin<string> { } public class IdentityUserLogin : IdentityUserLogin<string> { }

View File

@ -3,7 +3,7 @@
using System; using System;
namespace Microsoft.AspNet.Identity namespace Microsoft.AspNet.Identity.EntityFramework
{ {
public class IdentityUserRole : IdentityUserRole<string> { } public class IdentityUserRole : IdentityUserRole<string> { }

View File

@ -28,11 +28,6 @@ namespace Microsoft.Framework.DependencyInjection
return services.Configure<CookieAuthenticationOptions>(configureOptions, IdentityOptions.ApplicationCookieAuthenticationScheme); return services.Configure<CookieAuthenticationOptions>(configureOptions, IdentityOptions.ApplicationCookieAuthenticationScheme);
} }
public static IdentityBuilder AddIdentity(this IServiceCollection services)
{
return services.AddIdentity<IdentityUser, IdentityRole>(configureOptions: null);
}
public static IdentityBuilder AddIdentity<TUser, TRole>( public static IdentityBuilder AddIdentity<TUser, TRole>(
this IServiceCollection services) this IServiceCollection services)
where TUser : class where TUser : class

View File

@ -2,12 +2,13 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Linq.Expressions;
using Microsoft.AspNet.Identity.Test; using Microsoft.AspNet.Identity.Test;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test
{ {
public class InMemoryEFUserStoreTest : UserManagerTestBase<IdentityUser, IdentityRole> public class InMemoryEFUserStoreTest : UserManagerTestBase<IdentityUser, IdentityRole, string>
{ {
protected override object CreateTestContext() protected override object CreateTestContext()
{ {
@ -24,5 +25,37 @@ namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test
var store = new RoleStore<IdentityRole, InMemoryContext>((InMemoryContext)context); var store = new RoleStore<IdentityRole, InMemoryContext>((InMemoryContext)context);
services.AddInstance<IRoleStore<IdentityRole>>(store); services.AddInstance<IRoleStore<IdentityRole>>(store);
} }
protected override IdentityUser CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "",
bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = default(DateTimeOffset?), bool useNamePrefixAsUserName = false)
{
return new IdentityUser
{
UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()),
Email = email,
PhoneNumber = phoneNumber,
LockoutEnabled = lockoutEnabled,
LockoutEnd = lockoutEnd
};
}
protected override IdentityRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false)
{
var roleName = useRoleNamePrefixAsRoleName ? roleNamePrefix : string.Format("{0}{1}", roleNamePrefix, Guid.NewGuid());
return new IdentityRole(roleName);
}
protected override void SetUserPasswordHash(IdentityUser user, string hashedPassword)
{
user.PasswordHash = hashedPassword;
}
protected override Expression<Func<IdentityUser, bool>> UserNameEqualsPredicate(string userName) => u => u.UserName == userName;
protected override Expression<Func<IdentityRole, bool>> RoleNameEqualsPredicate(string roleName) => r => r.Name == roleName;
protected override Expression<Func<IdentityUser, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName);
protected override Expression<Func<IdentityRole, bool>> RoleNameStartsWithPredicate(string roleName) => r => r.Name.StartsWith(roleName);
} }
} }

View File

@ -18,7 +18,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test
services.AddEntityFramework().AddInMemoryStore(); services.AddEntityFramework().AddInMemoryStore();
var store = new RoleStore<IdentityRole>(new InMemoryContext()); var store = new RoleStore<IdentityRole>(new InMemoryContext());
services.AddInstance<IRoleStore<IdentityRole>>(store); services.AddInstance<IRoleStore<IdentityRole>>(store);
services.AddIdentity(); services.AddIdentity<IdentityUser,IdentityRole>();
var provider = services.BuildServiceProvider(); var provider = services.BuildServiceProvider();
var manager = provider.GetRequiredService<RoleManager<IdentityRole>>(); var manager = provider.GetRequiredService<RoleManager<IdentityRole>>();
Assert.NotNull(manager); Assert.NotNull(manager);
@ -31,7 +31,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.InMemory.Test
services.AddEntityFramework().AddInMemoryStore(); services.AddEntityFramework().AddInMemoryStore();
services.AddTransient<InMemoryContext>(); services.AddTransient<InMemoryContext>();
services.AddTransient<IRoleStore<IdentityRole>, RoleStore<IdentityRole, InMemoryContext>>(); services.AddTransient<IRoleStore<IdentityRole>, RoleStore<IdentityRole, InMemoryContext>>();
services.AddIdentity(); services.AddIdentity<IdentityUser, IdentityRole>();
services.AddSingleton<RoleManager<IdentityRole>>(); services.AddSingleton<RoleManager<IdentityRole>>();
var provider = services.BuildServiceProvider(); var provider = services.BuildServiceProvider();
var manager = provider.GetRequiredService<RoleManager<IdentityRole>>(); var manager = provider.GetRequiredService<RoleManager<IdentityRole>>();

View File

@ -2,6 +2,8 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Identity.Test; using Microsoft.AspNet.Identity.Test;
@ -14,7 +16,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
[TestCaseOrderer("Microsoft.AspNet.Identity.Test.PriorityOrderer", "Microsoft.AspNet.Identity.EntityFramework.Test")] [TestCaseOrderer("Microsoft.AspNet.Identity.Test.PriorityOrderer", "Microsoft.AspNet.Identity.EntityFramework.Test")]
public class DefaultPocoTest public class DefaultPocoTest
{ {
private readonly string ConnectionString = @"Server=(localdb)\mssqllocaldb;Database=DefaultSchemaTest" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year + ";Trusted_Connection=True;"; private readonly string ConnectionString = @"Server=(localdb)\mssqllocaldb;Database=DefaultSchemaTest" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year + ";Trusted_Connection=True;MultipleActiveResultSets=true";
public IdentityDbContext CreateContext(bool ensureCreated = false) public IdentityDbContext CreateContext(bool ensureCreated = false)
{ {
var db = DbUtil.Create(ConnectionString); var db = DbUtil.Create(ConnectionString);
@ -62,6 +64,148 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
IdentityResultAssert.IsSuccess(await userManager.DeleteAsync(user)); IdentityResultAssert.IsSuccess(await userManager.DeleteAsync(user));
} }
[Fact]
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());
}
[Fact]
public async Task CanIncludeUserLoginsTest()
{
// 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.AddLoginAsync(user, new UserLoginInfo("foo" + i, "bar" + i, "foo")));
}
user = dbContext.Users.Include(x => x.Logins).FirstOrDefault(x => x.UserName == username);
// Assert
Assert.NotNull(user);
Assert.NotNull(user.Logins);
Assert.Equal(10, user.Logins.Count());
}
[Fact]
public async Task CanIncludeUserRolesTest()
{
// 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 roleManager = builder.ApplicationServices.GetRequiredService<RoleManager<IdentityRole>>();
var dbContext = builder.ApplicationServices.GetRequiredService<IdentityDbContext>();
const string roleName = "Admin";
for (var i = 0; i < 10; i++)
{
IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(new IdentityRole(roleName + i)));
}
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.AddToRoleAsync(user, roleName + i));
}
user = dbContext.Users.Include(x => x.Roles).FirstOrDefault(x => x.UserName == username);
// Assert
Assert.NotNull(user);
Assert.NotNull(user.Roles);
Assert.Equal(10, user.Roles.Count());
for (var i = 0; i < 10; i++)
{
var role = dbContext.Roles.Include(r => r.Users).FirstOrDefault(r => r.Name == (roleName + i));
Assert.NotNull(role);
Assert.NotNull(role.Users);
Assert.Equal(1, role.Users.Count());
}
}
[Fact]
public async Task CanIncludeRoleClaimsTest()
{
// 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 roleManager = builder.ApplicationServices.GetRequiredService<RoleManager<IdentityRole>>();
var dbContext = builder.ApplicationServices.GetRequiredService<IdentityDbContext>();
var role = new IdentityRole("Admin");
IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(role));
for (var i = 0; i < 10; i++)
{
IdentityResultAssert.IsSuccess(await roleManager.AddClaimAsync(role, new Claim("foo" + i, "bar" + i)));
}
role = dbContext.Roles.Include(x => x.Claims).FirstOrDefault(x => x.Name == "Admin");
// Assert
Assert.NotNull(role);
Assert.NotNull(role.Claims);
Assert.Equal(10, role.Claims.Count());
}
[TestPriority(10000)] [TestPriority(10000)]
[Fact] [Fact]
public void DropDatabaseDone() public void DropDatabaseDone()

View File

@ -11,6 +11,7 @@ using Microsoft.AspNet.TestHost;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Runtime.Infrastructure; using Microsoft.Framework.Runtime.Infrastructure;
using Xunit; using Xunit;
using System.Linq.Expressions;
namespace Microsoft.AspNet.Identity.EntityFramework.Test namespace Microsoft.AspNet.Identity.EntityFramework.Test
{ {
@ -23,6 +24,34 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
public class TestDbContext : IdentityDbContext<TUser, TRole, TKey> { } public class TestDbContext : IdentityDbContext<TUser, TRole, TKey> { }
protected override TUser CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "",
bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = default(DateTimeOffset?), bool useNamePrefixAsUserName = false)
{
return new TUser
{
UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()),
Email = email,
PhoneNumber = phoneNumber,
LockoutEnabled = lockoutEnabled,
LockoutEnd = lockoutEnd
};
}
protected override TRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false)
{
var roleName = useRoleNamePrefixAsRoleName ? roleNamePrefix : string.Format("{0}{1}", roleNamePrefix, Guid.NewGuid());
return new TRole() { Name = roleName };
}
protected override Expression<Func<TRole, bool>> RoleNameEqualsPredicate(string roleName) => r => r.Name == roleName;
protected override Expression<Func<TUser, bool>> UserNameEqualsPredicate(string userName) => u => u.UserName == userName;
protected override Expression<Func<TRole, bool>> RoleNameStartsWithPredicate(string roleName) => r => r.Name.StartsWith(roleName);
protected override Expression<Func<TUser, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName);
[TestPriority(-1000)] [TestPriority(-1000)]
[Fact] [Fact]
public void DropDatabaseStart() public void DropDatabaseStart()
@ -69,6 +98,11 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
services.AddInstance<IRoleStore<TRole>>(new RoleStore<TRole, TestDbContext, TKey>((TestDbContext)context)); services.AddInstance<IRoleStore<TRole>>(new RoleStore<TRole, TestDbContext, TKey>((TestDbContext)context));
} }
protected override void SetUserPasswordHash(TUser user, string hashedPassword)
{
user.PasswordHash = hashedPassword;
}
public void EnsureDatabase() public void EnsureDatabase()
{ {
CreateContext(); CreateContext();
@ -168,8 +202,8 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
var context = CreateContext(); var context = CreateContext();
var manager = CreateManager(context); var manager = CreateManager(context);
var role = CreateRoleManager(context); var role = CreateRoleManager(context);
var admin = CreateRole("Admin"); var admin = CreateTestRole("Admin" + Guid.NewGuid().ToString());
var local = CreateRole("Local"); var local = CreateTestRole("Local" + Guid.NewGuid().ToString());
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, new UserLoginInfo("provider", user.Id.ToString(), "display"))); IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, new UserLoginInfo("provider", user.Id.ToString(), "display")));
IdentityResultAssert.IsSuccess(await role.CreateAsync(admin)); IdentityResultAssert.IsSuccess(await role.CreateAsync(admin));
@ -248,5 +282,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
Assert.Equal(1, (await manager.GetLoginsAsync(userByEmail)).Count); Assert.Equal(1, (await manager.GetLoginsAsync(userByEmail)).Count);
Assert.Equal(2, (await manager.GetRolesAsync(userByEmail)).Count); Assert.Equal(2, (await manager.GetRolesAsync(userByEmail)).Count);
} }
} }
} }

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Linq.Expressions;
using Microsoft.AspNet.Identity.Test; using Microsoft.AspNet.Identity.Test;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Linq.Expressions;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Identity.EntityFramework.Test namespace Microsoft.AspNet.Identity.EntityFramework.Test

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Linq.Expressions;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Identity.EntityFramework.Test namespace Microsoft.AspNet.Identity.EntityFramework.Test

View File

@ -3,6 +3,7 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Hosting;
@ -430,48 +431,41 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
} }
} }
// TODO: can we move these to UserManagerTestBase? protected override IdentityUser CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "",
[Fact] bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = default(DateTimeOffset?), bool useNamePrefixAsUserName = false)
public async Task DeleteRoleNonEmptySucceedsTest()
{ {
// Need fail if not empty? return new IdentityUser
var context = CreateTestContext(); {
var userMgr = CreateManager(context); UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()),
var roleMgr = CreateRoleManager(context); Email = email,
var role = new IdentityRole("deleteNonEmpty"); PhoneNumber = phoneNumber,
Assert.False(await roleMgr.RoleExistsAsync(role.Name)); LockoutEnabled = lockoutEnabled,
IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); LockoutEnd = lockoutEnd
var user = new IdentityUser("t"); };
IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user));
IdentityResultAssert.IsSuccess(await userMgr.AddToRoleAsync(user, role.Name));
var roles = await userMgr.GetRolesAsync(user);
Assert.Equal(1, roles.Count());
IdentityResultAssert.IsSuccess(await roleMgr.DeleteAsync(role));
Assert.Null(await roleMgr.FindByNameAsync(role.Name));
Assert.False(await roleMgr.RoleExistsAsync(role.Name));
// REVIEW: We should throw if deleteing a non empty role?
roles = await userMgr.GetRolesAsync(user);
Assert.Equal(0, roles.Count());
} }
// TODO: cascading deletes? navigation properties not working protected override IdentityRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false)
//[Fact] {
//public async Task DeleteUserRemovesFromRoleTest() var roleName = useRoleNamePrefixAsRoleName ? roleNamePrefix : string.Format("{0}{1}", roleNamePrefix, Guid.NewGuid());
//{ return new IdentityRole(roleName);
// // Need fail if not empty? }
// var userMgr = CreateManager();
// var roleMgr = CreateRoleManager(); protected override void SetUserPasswordHash(IdentityUser user, string hashedPassword)
// var role = new IdentityRole("deleteNonEmpty"); {
// Assert.False(await roleMgr.RoleExistsAsync(role.Name)); user.PasswordHash = hashedPassword;
// IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); }
// var user = new IdentityUser("t");
// IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user)); protected override Expression<Func<IdentityUser, bool>> UserNameEqualsPredicate(string userName) => u => u.UserName == userName;
// IdentityResultAssert.IsSuccess(await userMgr.AddToRoleAsync(user, role.Name));
// Assert.Equal(1, role.Users.Count); protected override Expression<Func<IdentityRole, bool>> RoleNameEqualsPredicate(string roleName) => r => r.Name == roleName;
// IdentityResultAssert.IsSuccess(await userMgr.DeleteAsync(user));
// role = await roleMgr.FindByIdAsync(role.Id); protected override Expression<Func<IdentityRole, bool>> RoleNameStartsWithPredicate(string roleName) => r => r.Name.StartsWith(roleName);
// Assert.Equal(0, role.Users.Count);
//} protected override Expression<Func<IdentityUser, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName);
}
public class ApplicationUser : IdentityUser
{
} }
} }

View File

@ -19,6 +19,7 @@ using Microsoft.AspNet.TestHost;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
using Shouldly; using Shouldly;
using Xunit; using Xunit;
using Microsoft.AspNet.Identity.Test;
namespace Microsoft.AspNet.Identity.InMemory namespace Microsoft.AspNet.Identity.InMemory
{ {
@ -162,8 +163,8 @@ namespace Microsoft.AspNet.Identity.InMemory
{ {
var req = context.Request; var req = context.Request;
var res = context.Response; var res = context.Response;
var userManager = context.RequestServices.GetRequiredService<UserManager<InMemoryUser>>(); var userManager = context.RequestServices.GetRequiredService<UserManager<TestUser>>();
var signInManager = context.RequestServices.GetRequiredService<SignInManager<InMemoryUser>>(); var signInManager = context.RequestServices.GetRequiredService<SignInManager<TestUser>>();
PathString remainder; PathString remainder;
if (req.Path == new PathString("/normal")) if (req.Path == new PathString("/normal"))
{ {
@ -171,7 +172,7 @@ namespace Microsoft.AspNet.Identity.InMemory
} }
else if (req.Path == new PathString("/createMe")) else if (req.Path == new PathString("/createMe"))
{ {
var result = await userManager.CreateAsync(new InMemoryUser("hao"), TestPassword); var result = await userManager.CreateAsync(new TestUser("hao"), TestPassword);
res.StatusCode = result.Succeeded ? 200 : 500; res.StatusCode = result.Succeeded ? 200 : 500;
} }
else if (req.Path == new PathString("/protected")) else if (req.Path == new PathString("/protected"))
@ -220,9 +221,9 @@ namespace Microsoft.AspNet.Identity.InMemory
}, },
services => services =>
{ {
services.AddIdentity<InMemoryUser, IdentityRole>(); services.AddIdentity<TestUser, TestRole>();
services.AddSingleton<IUserStore<InMemoryUser>, InMemoryUserStore<InMemoryUser>>(); services.AddSingleton<IUserStore<TestUser>, InMemoryUserStore<TestUser>>();
services.AddSingleton<IRoleStore<IdentityRole>, InMemoryRoleStore<IdentityRole>>(); services.AddSingleton<IRoleStore<TestRole>, InMemoryRoleStore<TestRole>>();
services.ConfigureIdentityApplicationCookie(configureAppCookie); services.ConfigureIdentityApplicationCookie(configureAppCookie);
}); });
server.BaseAddress = baseAddress; server.BaseAddress = baseAddress;

View File

@ -15,8 +15,6 @@ using Xunit;
namespace Microsoft.AspNet.Identity.InMemory.Test namespace Microsoft.AspNet.Identity.InMemory.Test
{ {
public class ApplicationUser : InMemoryUser { }
public class HttpSignInTest public class HttpSignInTest
{ {
[Theory] [Theory]
@ -37,19 +35,19 @@ namespace Microsoft.AspNet.Identity.InMemory.Test
contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddInstance(contextAccessor.Object); services.AddInstance(contextAccessor.Object);
services.AddIdentity<ApplicationUser, IdentityRole>(); services.AddIdentity<TestUser, TestRole>();
services.AddSingleton<IUserStore<ApplicationUser>, InMemoryUserStore<ApplicationUser>>(); services.AddSingleton<IUserStore<TestUser>, InMemoryUserStore<TestUser>>();
services.AddSingleton<IRoleStore<IdentityRole>, InMemoryRoleStore<IdentityRole>>(); services.AddSingleton<IRoleStore<TestRole>, InMemoryRoleStore<TestRole>>();
app.ApplicationServices = services.BuildServiceProvider(); app.ApplicationServices = services.BuildServiceProvider();
// Act // Act
var user = new ApplicationUser var user = new TestUser
{ {
UserName = "Yolo" UserName = "Yolo"
}; };
const string password = "Yol0Sw@g!"; const string password = "Yol0Sw@g!";
var userManager = app.ApplicationServices.GetRequiredService<UserManager<ApplicationUser>>(); var userManager = app.ApplicationServices.GetRequiredService<UserManager<TestUser>>();
var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<ApplicationUser>>(); var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<TestUser>>();
IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password)); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
var result = await signInManager.PasswordSignInAsync(user, password, isPersistent, false); var result = await signInManager.PasswordSignInAsync(user, password, isPersistent, false);

View File

@ -7,10 +7,11 @@ using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Test;
namespace Microsoft.AspNet.Identity.InMemory namespace Microsoft.AspNet.Identity.InMemory
{ {
public class InMemoryRoleStore<TRole> : IQueryableRoleStore<TRole>, IRoleClaimStore<TRole> where TRole : IdentityRole public class InMemoryRoleStore<TRole> : IQueryableRoleStore<TRole>, IRoleClaimStore<TRole> where TRole : TestRole
{ {
private readonly Dictionary<string, TRole> _roles = new Dictionary<string, TRole>(); private readonly Dictionary<string, TRole> _roles = new Dictionary<string, TRole>();
@ -81,7 +82,7 @@ namespace Microsoft.AspNet.Identity.InMemory
public Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) public Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{ {
role.Claims.Add(new IdentityRoleClaim<string> { ClaimType = claim.Type, ClaimValue = claim.Value, RoleId = role.Id }); role.Claims.Add(new TestRoleClaim<string> { ClaimType = claim.Type, ClaimValue = claim.Value, RoleId = role.Id });
return Task.FromResult(0); return Task.FromResult(0);
} }

View File

@ -2,12 +2,13 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Linq.Expressions;
using Microsoft.AspNet.Identity.Test; using Microsoft.AspNet.Identity.Test;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Identity.InMemory.Test namespace Microsoft.AspNet.Identity.InMemory.Test
{ {
public class InMemoryStoreTest : UserManagerTestBase<InMemoryUser, IdentityRole> public class InMemoryStoreTest : UserManagerTestBase<TestUser, TestRole>
{ {
protected override object CreateTestContext() protected override object CreateTestContext()
{ {
@ -16,12 +17,44 @@ namespace Microsoft.AspNet.Identity.InMemory.Test
protected override void AddUserStore(IServiceCollection services, object context = null) protected override void AddUserStore(IServiceCollection services, object context = null)
{ {
services.AddSingleton<IUserStore<InMemoryUser>, InMemoryUserStore<InMemoryUser>>(); services.AddSingleton<IUserStore<TestUser>, InMemoryUserStore<TestUser>>();
} }
protected override void AddRoleStore(IServiceCollection services, object context = null) protected override void AddRoleStore(IServiceCollection services, object context = null)
{ {
services.AddSingleton<IRoleStore<IdentityRole>, InMemoryRoleStore<IdentityRole>>(); services.AddSingleton<IRoleStore<TestRole>, InMemoryRoleStore<TestRole>>();
} }
protected override void SetUserPasswordHash(TestUser user, string hashedPassword)
{
user.PasswordHash = hashedPassword;
}
protected override TestUser CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "",
bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = default(DateTimeOffset?), bool useNamePrefixAsUserName = false)
{
return new TestUser
{
UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()),
Email = email,
PhoneNumber = phoneNumber,
LockoutEnabled = lockoutEnabled,
LockoutEnd = lockoutEnd
};
}
protected override TestRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false)
{
var roleName = useRoleNamePrefixAsRoleName ? roleNamePrefix : string.Format("{0}{1}", roleNamePrefix, Guid.NewGuid());
return new TestRole(roleName);
}
protected override Expression<Func<TestUser, bool>> UserNameEqualsPredicate(string userName) => u => u.UserName == userName;
protected override Expression<Func<TestRole, bool>> RoleNameEqualsPredicate(string roleName) => r => r.Name == roleName;
protected override Expression<Func<TestUser, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName);
protected override Expression<Func<TestRole, bool>> RoleNameStartsWithPredicate(string roleName) => r => r.Name.StartsWith(roleName);
} }
} }

View File

@ -7,33 +7,10 @@ using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Test;
namespace Microsoft.AspNet.Identity.InMemory namespace Microsoft.AspNet.Identity.InMemory
{ {
public class InMemoryUser : IdentityUser
{
public InMemoryUser() { }
public InMemoryUser(string userName) : base(userName) { }
/// <summary>
/// Roles for the user
/// </summary>
public virtual ICollection<IdentityUserRole> Roles { get; } = new List<IdentityUserRole>();
/// <summary>
/// Claims for the user
/// </summary>
public virtual ICollection<IdentityUserClaim> Claims { get; } = new List<IdentityUserClaim>();
/// <summary>
/// Associated logins for the user
/// </summary>
public virtual ICollection<IdentityUserLogin> Logins { get; } = new List<IdentityUserLogin>();
}
public class InMemoryUserStore<TUser> : public class InMemoryUserStore<TUser> :
IUserLoginStore<TUser>, IUserLoginStore<TUser>,
IUserRoleStore<TUser>, IUserRoleStore<TUser>,
@ -45,7 +22,7 @@ namespace Microsoft.AspNet.Identity.InMemory
IUserPhoneNumberStore<TUser>, IUserPhoneNumberStore<TUser>,
IQueryableUserStore<TUser>, IQueryableUserStore<TUser>,
IUserTwoFactorStore<TUser> IUserTwoFactorStore<TUser>
where TUser : InMemoryUser where TUser : TestUser
{ {
private readonly Dictionary<string, TUser> _logins = new Dictionary<string, TUser>(); private readonly Dictionary<string, TUser> _logins = new Dictionary<string, TUser>();
@ -66,7 +43,7 @@ namespace Microsoft.AspNet.Identity.InMemory
{ {
foreach (var claim in claims) foreach (var claim in claims)
{ {
user.Claims.Add(new IdentityUserClaim { ClaimType = claim.Type, ClaimValue = claim.Value, UserId = user.Id }); user.Claims.Add(new TestUserClaim { ClaimType = claim.Type, ClaimValue = claim.Value, UserId = user.Id });
} }
return Task.FromResult(0); return Task.FromResult(0);
} }
@ -185,7 +162,7 @@ namespace Microsoft.AspNet.Identity.InMemory
public virtual Task AddLoginAsync(TUser user, UserLoginInfo login, public virtual Task AddLoginAsync(TUser user, UserLoginInfo login,
CancellationToken cancellationToken = default(CancellationToken)) CancellationToken cancellationToken = default(CancellationToken))
{ {
user.Logins.Add(new IdentityUserLogin user.Logins.Add(new TestUserLogin
{ {
UserId = user.Id, UserId = user.Id,
ProviderKey = login.ProviderKey, ProviderKey = login.ProviderKey,
@ -328,7 +305,7 @@ namespace Microsoft.AspNet.Identity.InMemory
// RoleId == roleName for InMemory // RoleId == roleName for InMemory
public Task AddToRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken)) public Task AddToRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken))
{ {
user.Roles.Add(new IdentityUserRole { RoleId = role, UserId = user.Id }); user.Roles.Add(new TestUserRole { RoleId = role, UserId = user.Id });
return Task.FromResult(0); return Task.FromResult(0);
} }

View File

@ -18,8 +18,8 @@ namespace Microsoft.AspNet.Identity.Test
public void CanOverrideUserStore() public void CanOverrideUserStore()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity().AddUserStore<MyUberThingy>(); services.AddIdentity<TestUser,TestRole>().AddUserStore<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserStore<IdentityUser>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IUserStore<TestUser>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -27,8 +27,8 @@ namespace Microsoft.AspNet.Identity.Test
public void CanOverrideRoleStore() public void CanOverrideRoleStore()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity().AddRoleStore<MyUberThingy>(); services.AddIdentity<TestUser,TestRole>().AddRoleStore<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IRoleStore<IdentityRole>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IRoleStore<TestRole>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -36,8 +36,8 @@ namespace Microsoft.AspNet.Identity.Test
public void CanOverrideRoleValidator() public void CanOverrideRoleValidator()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity().AddRoleValidator<MyUberThingy>(); services.AddIdentity<TestUser,TestRole>().AddRoleValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IRoleValidator<IdentityRole>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IRoleValidator<TestRole>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -45,8 +45,8 @@ namespace Microsoft.AspNet.Identity.Test
public void CanOverrideUserValidator() public void CanOverrideUserValidator()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity().AddUserValidator<MyUberThingy>(); services.AddIdentity<TestUser,TestRole>().AddUserValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserValidator<IdentityUser>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IUserValidator<TestUser>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -54,8 +54,8 @@ namespace Microsoft.AspNet.Identity.Test
public void CanOverridePasswordValidator() public void CanOverridePasswordValidator()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity().AddPasswordValidator<MyUberThingy>(); services.AddIdentity<TestUser,TestRole>().AddPasswordValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IPasswordValidator<IdentityUser>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IPasswordValidator<TestUser>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -85,16 +85,16 @@ namespace Microsoft.AspNet.Identity.Test
public void EnsureDefaultServices() public void EnsureDefaultServices()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity(); services.AddIdentity<TestUser,TestRole>();
var provider = services.BuildServiceProvider(); var provider = services.BuildServiceProvider();
var userValidator = provider.GetRequiredService<IUserValidator<IdentityUser>>() as UserValidator<IdentityUser>; var userValidator = provider.GetRequiredService<IUserValidator<TestUser>>() as UserValidator<TestUser>;
Assert.NotNull(userValidator); Assert.NotNull(userValidator);
var pwdValidator = provider.GetRequiredService<IPasswordValidator<IdentityUser>>() as PasswordValidator<IdentityUser>; var pwdValidator = provider.GetRequiredService<IPasswordValidator<TestUser>>() as PasswordValidator<TestUser>;
Assert.NotNull(pwdValidator); Assert.NotNull(pwdValidator);
var hasher = provider.GetRequiredService<IPasswordHasher<IdentityUser>>() as PasswordHasher<IdentityUser>; var hasher = provider.GetRequiredService<IPasswordHasher<TestUser>>() as PasswordHasher<TestUser>;
Assert.NotNull(hasher); Assert.NotNull(hasher);
} }
@ -102,31 +102,31 @@ namespace Microsoft.AspNet.Identity.Test
public void EnsureDefaultTokenProviders() public void EnsureDefaultTokenProviders()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity().AddDefaultTokenProviders(); services.AddIdentity<TestUser,TestRole>().AddDefaultTokenProviders();
var provider = services.BuildServiceProvider(); var provider = services.BuildServiceProvider();
var tokenProviders = provider.GetRequiredService<IEnumerable<IUserTokenProvider<IdentityUser>>>(); var tokenProviders = provider.GetRequiredService<IEnumerable<IUserTokenProvider<TestUser>>>();
Assert.Equal(3, tokenProviders.Count()); Assert.Equal(3, tokenProviders.Count());
} }
private class MyUberThingy : IUserValidator<IdentityUser>, IPasswordValidator<IdentityUser>, IRoleValidator<IdentityRole>, IUserStore<IdentityUser>, IRoleStore<IdentityRole> private class MyUberThingy : IUserValidator<TestUser>, IPasswordValidator<TestUser>, IRoleValidator<TestRole>, IUserStore<TestUser>, IRoleStore<TestRole>
{ {
public Task<IdentityResult> CreateAsync(IdentityRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> CreateAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> CreateAsync(IdentityUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> CreateAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> DeleteAsync(IdentityRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> DeleteAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> DeleteAsync(IdentityUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> DeleteAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@ -136,97 +136,97 @@ namespace Microsoft.AspNet.Identity.Test
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) public Task<TestUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken)) public Task<TestUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetNormalizedRoleNameAsync(IdentityRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetNormalizedRoleNameAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetNormalizedUserNameAsync(IdentityUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetNormalizedUserNameAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetRoleIdAsync(IdentityRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetRoleIdAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetRoleNameAsync(IdentityRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetRoleNameAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetUserIdAsync(IdentityUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetUserIdAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetUserNameAsync(IdentityUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetUserNameAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetNormalizedRoleNameAsync(IdentityRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetNormalizedRoleNameAsync(TestRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetNormalizedUserNameAsync(IdentityUser user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetNormalizedUserNameAsync(TestUser user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetRoleNameAsync(IdentityRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetRoleNameAsync(TestRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetUserNameAsync(IdentityUser user, string userName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetUserNameAsync(TestUser user, string userName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> UpdateAsync(IdentityRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> UpdateAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> UpdateAsync(IdentityUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> UpdateAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> ValidateAsync(RoleManager<IdentityRole> manager, IdentityRole role) public Task<IdentityResult> ValidateAsync(RoleManager<TestRole> manager, TestRole role)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> ValidateAsync(UserManager<IdentityUser> manager, IdentityUser user) public Task<IdentityResult> ValidateAsync(UserManager<TestUser> manager, TestUser user)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> ValidateAsync(UserManager<IdentityUser> manager, IdentityUser user, string password) public Task<IdentityResult> ValidateAsync(UserManager<TestUser> manager, TestUser user, string password)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
Task<IdentityRole> IRoleStore<IdentityRole>.FindByIdAsync(string roleId, CancellationToken cancellationToken) Task<TestRole> IRoleStore<TestRole>.FindByIdAsync(string roleId, CancellationToken cancellationToken)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
Task<IdentityRole> IRoleStore<IdentityRole>.FindByNameAsync(string roleName, CancellationToken cancellationToken) Task<TestRole> IRoleStore<TestRole>.FindByNameAsync(string roleName, CancellationToken cancellationToken)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }

View File

@ -65,7 +65,7 @@ namespace Microsoft.AspNet.Identity.Test
Assert.Equal(roleClaimType, config.Get("identity:claimsidentity:roleclaimtype")); Assert.Equal(roleClaimType, config.Get("identity:claimsidentity:roleclaimtype"));
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity(); services.AddIdentity<TestUser,TestRole>();
services.ConfigureIdentity(config.GetSubKey("identity")); services.ConfigureIdentity(config.GetSubKey("identity"));
var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>(); var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>();
Assert.NotNull(accessor); Assert.NotNull(accessor);
@ -96,7 +96,7 @@ namespace Microsoft.AspNet.Identity.Test
var config = new Configuration(new MemoryConfigurationSource(dic)); var config = new Configuration(new MemoryConfigurationSource(dic));
var services = new ServiceCollection(); var services = new ServiceCollection();
services.ConfigureIdentity(config.GetSubKey("identity")); services.ConfigureIdentity(config.GetSubKey("identity"));
services.AddIdentity<IdentityUser, IdentityRole>(o => { o.User.RequireUniqueEmail = false; o.Lockout.MaxFailedAccessAttempts++; }); services.AddIdentity<TestUser, TestRole>(o => { o.User.RequireUniqueEmail = false; o.Lockout.MaxFailedAccessAttempts++; });
var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>(); var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>();
Assert.NotNull(accessor); Assert.NotNull(accessor);
var options = accessor.Options; var options = accessor.Options;
@ -116,7 +116,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.ConfigureOptions<PasswordsNegativeLengthSetup>(); .ConfigureOptions<PasswordsNegativeLengthSetup>();
services.AddIdentity(); services.AddIdentity<TestUser,TestRole>();
var serviceProvider = services.BuildServiceProvider(); var serviceProvider = services.BuildServiceProvider();
var setup = serviceProvider.GetRequiredService<IConfigureOptions<IdentityOptions>>(); var setup = serviceProvider.GetRequiredService<IConfigureOptions<IdentityOptions>>();
@ -137,7 +137,7 @@ namespace Microsoft.AspNet.Identity.Test
var services = new ServiceCollection() var services = new ServiceCollection()
.AddOptions() .AddOptions()
.ConfigureIdentity(options => options.User.RequireUniqueEmail = true); .ConfigureIdentity(options => options.User.RequireUniqueEmail = true);
services.AddIdentity(); services.AddIdentity<TestUser,TestRole>();
var serviceProvider = services.BuildServiceProvider(); var serviceProvider = services.BuildServiceProvider();
var optionsGetter = serviceProvider.GetRequiredService<IOptions<IdentityOptions>>(); var optionsGetter = serviceProvider.GetRequiredService<IOptions<IdentityOptions>>();

View File

@ -26,7 +26,7 @@ namespace Microsoft.AspNet.Identity.Test
public async Task ValidateThrowsWithNullTest() public async Task ValidateThrowsWithNullTest()
{ {
// Setup // Setup
var validator = new PasswordValidator<IdentityUser>(); var validator = new PasswordValidator<TestUser>();
// Act // Act
// Assert // Assert
@ -42,8 +42,8 @@ namespace Microsoft.AspNet.Identity.Test
public async Task FailsIfTooShortTests(string input) public async Task FailsIfTooShortTests(string input)
{ {
const string error = "Passwords must be at least 6 characters."; const string error = "Passwords must be at least 6 characters.";
var manager = MockHelpers.TestUserManager<IdentityUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<IdentityUser>(); var valid = new PasswordValidator<TestUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonLetterOrDigit = false; manager.Options.Password.RequireNonLetterOrDigit = false;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -56,8 +56,8 @@ namespace Microsoft.AspNet.Identity.Test
[InlineData("aaaaaaaaaaa")] [InlineData("aaaaaaaaaaa")]
public async Task SuccessIfLongEnoughTests(string input) public async Task SuccessIfLongEnoughTests(string input)
{ {
var manager = MockHelpers.TestUserManager<IdentityUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<IdentityUser>(); var valid = new PasswordValidator<TestUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonLetterOrDigit = false; manager.Options.Password.RequireNonLetterOrDigit = false;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -70,8 +70,8 @@ namespace Microsoft.AspNet.Identity.Test
[InlineData("aaaaaaaaaaa")] [InlineData("aaaaaaaaaaa")]
public async Task FailsWithoutRequiredNonAlphanumericTests(string input) public async Task FailsWithoutRequiredNonAlphanumericTests(string input)
{ {
var manager = MockHelpers.TestUserManager<IdentityUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<IdentityUser>(); var valid = new PasswordValidator<TestUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonLetterOrDigit = true; manager.Options.Password.RequireNonLetterOrDigit = true;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -87,8 +87,8 @@ namespace Microsoft.AspNet.Identity.Test
[InlineData("!!!!!!")] [InlineData("!!!!!!")]
public async Task SucceedsWithRequiredNonAlphanumericTests(string input) public async Task SucceedsWithRequiredNonAlphanumericTests(string input)
{ {
var manager = MockHelpers.TestUserManager<IdentityUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<IdentityUser>(); var valid = new PasswordValidator<TestUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonLetterOrDigit = true; manager.Options.Password.RequireNonLetterOrDigit = true;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -111,8 +111,8 @@ namespace Microsoft.AspNet.Identity.Test
const string lowerError = "Passwords must have at least one lowercase ('a'-'z')."; const string lowerError = "Passwords must have at least one lowercase ('a'-'z').";
const string digitError = "Passwords must have at least one digit ('0'-'9')."; const string digitError = "Passwords must have at least one digit ('0'-'9').";
const string lengthError = "Passwords must be at least 6 characters."; const string lengthError = "Passwords must be at least 6 characters.";
var manager = MockHelpers.TestUserManager<IdentityUser>(); var manager = MockHelpers.TestUserManager<TestUser>();
var valid = new PasswordValidator<IdentityUser>(); var valid = new PasswordValidator<TestUser>();
var errors = new List<string>(); var errors = new List<string>();
if ((errorMask & Errors.Length) != Errors.None) if ((errorMask & Errors.Length) != Errors.None)
{ {

View File

@ -35,23 +35,23 @@ namespace Microsoft.AspNet.Identity.Test
[InlineData(false)] [InlineData(false)]
public async Task OnValidatePrincipalTestSuccess(bool isPersistent) public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
{ {
var user = new IdentityUser("test"); var user = new TestUser("test");
var userManager = MockHelpers.MockUserManager<IdentityUser>(); var userManager = MockHelpers.MockUserManager<TestUser>();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<IdentityUser>>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero }; var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
var options = new Mock<IOptions<IdentityOptions>>(); var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Options).Returns(identityOptions); options.Setup(a => a.Options).Returns(identityOptions);
var httpContext = new Mock<HttpContext>(); var httpContext = new Mock<HttpContext>();
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object, var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
contextAccessor.Object, claimsManager.Object, options.Object, null); contextAccessor.Object, claimsManager.Object, options.Object, null);
signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable(); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable();
signInManager.Setup(s => s.SignInAsync(user, isPersistent, null)).Returns(Task.FromResult(0)).Verifiable(); signInManager.Setup(s => s.SignInAsync(user, isPersistent, null)).Returns(Task.FromResult(0)).Verifiable();
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddInstance(options.Object); services.AddInstance(options.Object);
services.AddInstance(signInManager.Object); services.AddInstance(signInManager.Object);
services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<IdentityUser>()); services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme); var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
@ -72,22 +72,22 @@ namespace Microsoft.AspNet.Identity.Test
[Fact] [Fact]
public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails() public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails()
{ {
var user = new IdentityUser("test"); var user = new TestUser("test");
var userManager = MockHelpers.MockUserManager<IdentityUser>(); var userManager = MockHelpers.MockUserManager<TestUser>();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<IdentityUser>>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero }; var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
var options = new Mock<IOptions<IdentityOptions>>(); var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Options).Returns(identityOptions); options.Setup(a => a.Options).Returns(identityOptions);
var httpContext = new Mock<HttpContext>(); var httpContext = new Mock<HttpContext>();
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object, var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
contextAccessor.Object, claimsManager.Object, options.Object, null); contextAccessor.Object, claimsManager.Object, options.Object, null);
signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(null).Verifiable(); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(null).Verifiable();
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddInstance(options.Object); services.AddInstance(options.Object);
services.AddInstance(signInManager.Object); services.AddInstance(signInManager.Object);
services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<IdentityUser>()); services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme); var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
@ -107,22 +107,22 @@ namespace Microsoft.AspNet.Identity.Test
[Fact] [Fact]
public async Task OnValidateIdentityRejectsWhenNoIssuedUtc() public async Task OnValidateIdentityRejectsWhenNoIssuedUtc()
{ {
var user = new IdentityUser("test"); var user = new TestUser("test");
var httpContext = new Mock<HttpContext>(); var httpContext = new Mock<HttpContext>();
var userManager = MockHelpers.MockUserManager<IdentityUser>(); var userManager = MockHelpers.MockUserManager<TestUser>();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<IdentityUser>>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero }; var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
var options = new Mock<IOptions<IdentityOptions>>(); var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Options).Returns(identityOptions); options.Setup(a => a.Options).Returns(identityOptions);
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object, var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
contextAccessor.Object, claimsManager.Object, options.Object, null); contextAccessor.Object, claimsManager.Object, options.Object, null);
signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(null).Verifiable(); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(null).Verifiable();
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddInstance(options.Object); services.AddInstance(options.Object);
services.AddInstance(signInManager.Object); services.AddInstance(signInManager.Object);
services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<IdentityUser>()); services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme); var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
@ -142,23 +142,23 @@ namespace Microsoft.AspNet.Identity.Test
[Fact] [Fact]
public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired() public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired()
{ {
var user = new IdentityUser("test"); var user = new TestUser("test");
var httpContext = new Mock<HttpContext>(); var httpContext = new Mock<HttpContext>();
var userManager = MockHelpers.MockUserManager<IdentityUser>(); var userManager = MockHelpers.MockUserManager<TestUser>();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<IdentityUser>>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.FromDays(1) }; var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.FromDays(1) };
var options = new Mock<IOptions<IdentityOptions>>(); var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Options).Returns(identityOptions); options.Setup(a => a.Options).Returns(identityOptions);
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object, var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
contextAccessor.Object, claimsManager.Object, options.Object, null); contextAccessor.Object, claimsManager.Object, options.Object, null);
signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).Throws(new Exception("Shouldn't be called")); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).Throws(new Exception("Shouldn't be called"));
signInManager.Setup(s => s.SignInAsync(user, false, null)).Throws(new Exception("Shouldn't be called")); signInManager.Setup(s => s.SignInAsync(user, false, null)).Throws(new Exception("Shouldn't be called"));
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddInstance(options.Object); services.AddInstance(options.Object);
services.AddInstance(signInManager.Object); services.AddInstance(signInManager.Object);
services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<IdentityUser>()); services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme); var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

View File

@ -68,14 +68,14 @@ namespace Microsoft.AspNet.Identity.Test
[Fact] [Fact]
public void ConstructorNullChecks() public void ConstructorNullChecks()
{ {
Assert.Throws<ArgumentNullException>("userManager", () => new SignInManager<IdentityUser>(null, null, null, null, null)); Assert.Throws<ArgumentNullException>("userManager", () => new SignInManager<TestUser>(null, null, null, null, null));
var userManager = MockHelpers.MockUserManager<IdentityUser>().Object; var userManager = MockHelpers.MockUserManager<TestUser>().Object;
Assert.Throws<ArgumentNullException>("contextAccessor", () => new SignInManager<IdentityUser>(userManager, null, null, null)); Assert.Throws<ArgumentNullException>("contextAccessor", () => new SignInManager<TestUser>(userManager, null, null, null));
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
Assert.Throws<ArgumentNullException>("contextAccessor", () => new SignInManager<IdentityUser>(userManager, contextAccessor.Object, null, null)); Assert.Throws<ArgumentNullException>("contextAccessor", () => new SignInManager<TestUser>(userManager, contextAccessor.Object, null, null));
var context = new Mock<HttpContext>(); var context = new Mock<HttpContext>();
contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
Assert.Throws<ArgumentNullException>("claimsFactory", () => new SignInManager<IdentityUser>(userManager, contextAccessor.Object, null, null)); Assert.Throws<ArgumentNullException>("claimsFactory", () => new SignInManager<TestUser>(userManager, contextAccessor.Object, null, null));
} }
//TODO: Mock fails in K (this works fine in net45) //TODO: Mock fails in K (this works fine in net45)

View File

@ -7,6 +7,7 @@ using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Test;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
using Moq; using Moq;
using Xunit; using Xunit;
@ -20,7 +21,7 @@ namespace Microsoft.AspNet.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddTransient<IUserStore<TestUser>, NoopUserStore>(); .AddTransient<IUserStore<TestUser>, NoopUserStore>();
services.AddIdentity<TestUser, IdentityRole>(); services.AddIdentity<TestUser, TestRole>();
var manager = services.BuildServiceProvider().GetRequiredService<UserManager<TestUser>>(); var manager = services.BuildServiceProvider().GetRequiredService<UserManager<TestUser>>();
Assert.NotNull(manager.PasswordHasher); Assert.NotNull(manager.PasswordHasher);
Assert.NotNull(manager.Store); Assert.NotNull(manager.Store);
@ -544,8 +545,8 @@ namespace Microsoft.AspNet.Identity.Test
[Fact] [Fact]
public async Task SecurityStampMethodsFailWhenStoreNotImplemented() public async Task SecurityStampMethodsFailWhenStoreNotImplemented()
{ {
var store = new Mock<IUserStore<IdentityUser>>(); var store = new Mock<IUserStore<TestUser>>();
store.Setup(x => x.GetUserIdAsync(It.IsAny<IdentityUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(Guid.NewGuid().ToString())); store.Setup(x => x.GetUserIdAsync(It.IsAny<TestUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(Guid.NewGuid().ToString()));
var manager = MockHelpers.TestUserManager(store.Object); var manager = MockHelpers.TestUserManager(store.Object);
Assert.False(manager.SupportsUserSecurityStamp); Assert.False(manager.SupportsUserSecurityStamp);
await Assert.ThrowsAsync<NotSupportedException>(() => manager.UpdateSecurityStampAsync(null)); await Assert.ThrowsAsync<NotSupportedException>(() => manager.UpdateSecurityStampAsync(null));
@ -636,8 +637,8 @@ namespace Microsoft.AspNet.Identity.Test
[Fact] [Fact]
public async Task ResetTokenCallNoopForTokenValueZero() public async Task ResetTokenCallNoopForTokenValueZero()
{ {
var user = new IdentityUser() { UserName = Guid.NewGuid().ToString()}; var user = new TestUser() { UserName = Guid.NewGuid().ToString()};
var store = new Mock<IUserLockoutStore<IdentityUser>>(); var store = new Mock<IUserLockoutStore<TestUser>>();
store.Setup(x => x.ResetAccessFailedCountAsync(user, It.IsAny<CancellationToken>())).Returns(() => store.Setup(x => x.ResetAccessFailedCountAsync(user, It.IsAny<CancellationToken>())).Returns(() =>
{ {
throw new Exception(); throw new Exception();
@ -1372,7 +1373,7 @@ namespace Microsoft.AspNet.Identity.Test
var describer = new TestErrorDescriber(); var describer = new TestErrorDescriber();
services.AddInstance<IdentityErrorDescriber>(describer) services.AddInstance<IdentityErrorDescriber>(describer)
.AddInstance<IUserStore<TestUser>>(store.Object) .AddInstance<IUserStore<TestUser>>(store.Object)
.AddIdentity<TestUser, IdentityRole>(); .AddIdentity<TestUser, TestRole>();
var manager = services.BuildServiceProvider().GetRequiredService<UserManager<TestUser>>(); var manager = services.BuildServiceProvider().GetRequiredService<UserManager<TestUser>>();

View File

@ -1,7 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Identity.Test
{
public class ApplicationUser : IdentityUser { }
}

View File

@ -1,11 +1,70 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace Microsoft.AspNet.Identity.Test namespace Microsoft.AspNet.Identity.Test
{ {
public class TestRole /// <summary>
/// Represents a Role entity
/// </summary>
public class TestRole : TestRole<string>
{ {
public string Id { get; private set; } /// <summary>
public string Name { get; set; } /// Constructor
/// </summary>
public TestRole()
{
Id = Guid.NewGuid().ToString();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="roleName"></param>
public TestRole(string roleName) : this()
{
Name = roleName;
}
}
/// <summary>
/// Represents a Role entity
/// </summary>
/// <typeparam name="TKey"></typeparam>
public class TestRole<TKey> where TKey : IEquatable<TKey>
{
public TestRole() { }
/// <summary>
/// Constructor
/// </summary>
/// <param name="roleName"></param>
public TestRole(string roleName) : this()
{
Name = roleName;
}
/// <summary>
/// Role id
/// </summary>
public virtual TKey Id { get; set; }
/// <summary>
/// Navigation property for claims in the role
/// </summary>
public virtual ICollection<TestRoleClaim<TKey>> Claims { get; private set; } = new List<TestRoleClaim<TKey>>();
/// <summary>
/// Role name
/// </summary>
public virtual string Name { get; set; }
public virtual string NormalizedName { get; set; }
/// <summary>
/// A random value that should change whenever a role is persisted to the store
/// </summary>
public virtual string ConcurrencyStamp { get; set; } = Guid.NewGuid().ToString();
} }
} }

View File

@ -0,0 +1,36 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNet.Identity.Test
{
public class TestRoleClaim : TestRoleClaim<string> { }
/// <summary>
/// EntityType that represents one specific role claim
/// </summary>
/// <typeparam name="TKey"></typeparam>
public class TestRoleClaim<TKey> where TKey : IEquatable<TKey>
{
/// <summary>
/// Primary key
/// </summary>
public virtual int Id { get; set; }
/// <summary>
/// User Id for the role this claim belongs to
/// </summary>
public virtual TKey RoleId { get; set; }
/// <summary>
/// Claim type
/// </summary>
public virtual string ClaimType { get; set; }
/// <summary>
/// Claim value
/// </summary>
public virtual string ClaimValue { get; set; }
}
}

View File

@ -2,18 +2,104 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Collections.Generic;
namespace Microsoft.AspNet.Identity.Test namespace Microsoft.AspNet.Identity.Test
{ {
public class TestUser public class TestUser : TestUser<string>
{ {
public TestUser() public TestUser()
{ {
Id = Guid.NewGuid().ToString(); Id = Guid.NewGuid().ToString();
} }
public string Id { get; private set; } public TestUser(string userName) : this()
public string UserName { get; set; } {
public string Email { get; set; } UserName = userName;
}
} }
}
public class TestUser<TKey> where TKey : IEquatable<TKey>
{
public TestUser() { }
public TestUser(string userName) : this()
{
UserName = userName;
}
public virtual TKey Id { get; set; }
public virtual string UserName { get; set; }
public virtual string NormalizedUserName { get; set; }
/// <summary>
/// Email
/// </summary>
public virtual string Email { get; set; }
public virtual string NormalizedEmail { get; set; }
/// <summary>
/// True if the email is confirmed, default is false
/// </summary>
public virtual bool EmailConfirmed { get; set; }
/// <summary>
/// The salted/hashed form of the user password
/// </summary>
public virtual string PasswordHash { get; set; }
/// <summary>
/// A random value that should change whenever a users credentials change (password changed, login removed)
/// </summary>
public virtual string SecurityStamp { get; set; }
/// <summary>
/// A random value that should change whenever a user is persisted to the store
/// </summary>
public virtual string ConcurrencyStamp { get; set; } = Guid.NewGuid().ToString();
/// <summary>
/// PhoneNumber for the user
/// </summary>
public virtual string PhoneNumber { get; set; }
/// <summary>
/// True if the phone number is confirmed, default is false
/// </summary>
public virtual bool PhoneNumberConfirmed { get; set; }
/// <summary>
/// Is two factor enabled for the user
/// </summary>
public virtual bool TwoFactorEnabled { get; set; }
/// <summary>
/// DateTime in UTC when lockout ends, any time in the past is considered not locked out.
/// </summary>
public virtual DateTimeOffset? LockoutEnd { get; set; }
/// <summary>
/// Is lockout enabled for this user
/// </summary>
public virtual bool LockoutEnabled { get; set; }
/// <summary>
/// Used to record failures for the purposes of lockout
/// </summary>
public virtual int AccessFailedCount { get; set; }
/// <summary>
/// Navigation property for users in the role
/// </summary>
public virtual ICollection<TestUserRole<TKey>> Roles { get; private set; } = new List<TestUserRole<TKey>>();
/// <summary>
/// Navigation property for users claims
/// </summary>
public virtual ICollection<TestUserClaim<TKey>> Claims { get; private set; } = new List<TestUserClaim<TKey>>();
/// <summary>
/// Navigation property for users logins
/// </summary>
public virtual ICollection<TestUserLogin<TKey>> Logins { get; private set; } = new List<TestUserLogin<TKey>>();
}
}

View File

@ -0,0 +1,36 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNet.Identity.Test
{
public class TestUserClaim : TestUserClaim<string> { }
/// <summary>
/// EntityType that represents one specific user claim
/// </summary>
/// <typeparam name="TKey"></typeparam>
public class TestUserClaim<TKey> where TKey : IEquatable<TKey>
{
/// <summary>
/// Primary key
/// </summary>
public virtual int Id { get; set; }
/// <summary>
/// User Id for the user who owns this claim
/// </summary>
public virtual TKey UserId { get; set; }
/// <summary>
/// Claim type
/// </summary>
public virtual string ClaimType { get; set; }
/// <summary>
/// Claim value
/// </summary>
public virtual string ClaimValue { get; set; }
}
}

View File

@ -0,0 +1,36 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNet.Identity.Test
{
public class TestUserLogin : TestUserLogin<string> { }
/// <summary>
/// Entity type for a user's login (i.e. facebook, google)
/// </summary>
/// <typeparam name="TKey"></typeparam>
public class TestUserLogin<TKey> where TKey : IEquatable<TKey>
{
/// <summary>
/// The login provider for the login (i.e. facebook, google)
/// </summary>
public virtual string LoginProvider { get; set; }
/// <summary>
/// Key representing the login for the provider
/// </summary>
public virtual string ProviderKey { get; set; }
/// <summary>
/// Display name for the login
/// </summary>
public virtual string ProviderDisplayName { get; set; }
/// <summary>
/// User Id for the user who owns this login
/// </summary>
public virtual TKey UserId { get; set; }
}
}

View File

@ -0,0 +1,26 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNet.Identity.Test
{
public class TestUserRole : TestUserRole<string> { }
/// <summary>
/// EntityType that represents a user belonging to a role
/// </summary>
/// <typeparam name="TKey"></typeparam>
public class TestUserRole<TKey> where TKey : IEquatable<TKey>
{
/// <summary>
/// UserId for the user that is in the role
/// </summary>
public virtual TKey UserId { get; set; }
/// <summary>
/// RoleId for the role
/// </summary>
public virtual TKey RoleId { get; set; }
}
}

File diff suppressed because it is too large Load Diff