我想说,ASP.NET Identity 有点过于复杂。
2014 年 8 月,他们宣布了新版本2.1事情又发生了变化。
首先我们要摆脱EntityFramework
:
Uninstall-Package Microsoft.AspNet.Identity.EntityFramework
现在我们实现我们自己的定义User
实现接口IUser
(微软.AspNet.Identity):
public class User: IUser<int>
{
public User()
{
this.Roles = new List<string>();
this.Claims = new List<UserClaim>();
}
public User(string userName)
: this()
{
this.UserName = userName;
}
public User(int id, string userName): this()
{
this.Id = Id;
this.UserName = userName;
}
public int Id { get; set; }
public string UserName { get; set; }
public string PasswordHash { get; set; }
public bool LockoutEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool TwoFactorEnabled { get; set; }
public IList<string> Roles { get; private set; }
public IList<UserClaim> Claims { get; private set; }
}
正如你所看到的,我已经定义了我的类型Id
(int).
然后你必须定义你的自定义UserManager
继承自Microsoft.AspNet.Identity.UserManager
指定您的用户类型和密钥类型。
public class UserManager : UserManager<User, int>
{
public UserManager(IUserStore<User, int> store): base(store)
{
this.UserLockoutEnabledByDefault = false;
// this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(10);
// this.MaxFailedAccessAttemptsBeforeLockout = 10;
this.UserValidator = new UserValidator<User, int>(this)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = false
};
// Configure validation logic for passwords
this.PasswordValidator = new PasswordValidator
{
RequiredLength = 4,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
}
}
我已经在这里实现了我的验证规则,但如果您愿意,也可以将其保留在外面。
UserManager
需要一个UserStore
(用户存储库).
您将在此处定义数据库逻辑。有几个接口需要实现。但并非所有这些都是强制性的。
public class UserStore :
IUserStore<User, int>,
IUserPasswordStore<User, int>,
IUserLockoutStore<User, int>,
IUserTwoFactorStore<User, int>,
IUserRoleStore<User, int>,
IUserClaimStore<User, int>
{
// You can inject connection string or db session
public UserStore()
{
}
}
我没有包含每个接口的所有方法。完成后,您将能够编写新用户:
public System.Threading.Tasks.Task CreateAsync(User user)
{
}
通过Id获取:
public System.Threading.Tasks.Task<User> FindByIdAsync(int userId)
{
}
等等。
然后你需要定义你的SignInManager
继承自Microsoft.AspNet.Identity.Owin.SignInManager
.
public class SignInManager: SignInManager<User, int>
{
public SignInManager(UserManager userManager, IAuthenticationManager authenticationManager): base(userManager, authenticationManager)
{
}
public override Task SignInAsync(User user, bool isPersistent, bool rememberBrowser)
{
return base.SignInAsync(user, isPersistent, rememberBrowser);
}
}
我只实施过SignInAsync
:它将生成一个声明身份.
差不多就这样了。
现在在你的Startup
你必须讲的课Owin
如何创建UserManager
和SignInManager
.
app.CreatePerOwinContext<Custom.Identity.UserManager>(() => new Custom.Identity.UserManager(new Custom.Identity.UserStore()));
// app.CreatePerOwinContext<Custom.Identity.RoleManager>(() => new Custom.Identity.RoleManager(new Custom.Identity.RoleStore()));
app.CreatePerOwinContext<Custom.Identity.SignInService>((options, context) => new Custom.Identity.SignInService(context.GetUserManager<Custom.Identity.UserManager>(), context.Authentication));
我没有使用您在默认模板中找到的工厂,因为我想让事情尽可能简单.
并使您的应用程序能够使用 cookie:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<Custom.Identity.UserManager, Custom.Identity.User, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) =>
{
var userIdentity = manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
return (userIdentity);
},
getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))
)}
});
现在在您的帐户控制器 - 或负责登录的控制器 - 您将必须获得UserManager
和SignInManager
:
public Custom.Identity.SignInManager SignInManager
{
get
{
return HttpContext.GetOwinContext().Get<Custom.Identity.SignInManager>();
}
}
public Custom.Identity.UserManager UserManager
{
get
{
return HttpContext.GetOwinContext().GetUserManager<Custom.Identity.UserManager>();
}
}
您将使用SignInManager
对于登录:
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
and the UserManager
要创建用户,添加角色和声明:
if (ModelState.IsValid)
{
var user = new Custom.Identity.User() { UserName = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// await UserManager.AddToRoleAsync(user.Id, "Administrators");
// await UserManager.AddClaimAsync(user.Id, new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Country, "England"));
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
这看起来很复杂……而且确实……有点复杂。
如果您想了解更多相关信息,这里有一个很好的解释here and here.
如果你想运行一些代码并看看它是如何工作的,我已经整理了一些code它适用于Biggy(因为我不想浪费太多时间定义表格之类的东西)。
如果您有机会从 github 存储库下载我的代码,您会注意到我创建了一个辅助项目 (Custom.Identity),其中保留了我的所有ASP.NET 身份东西。
唯一的nuget您需要的包有:
- Microsoft.AspNet.Identity.Core
- 微软.AspNet.Identity.Owin