为现有项目配置身份并不难。您必须安装一些 NuGet 包并进行一些小配置。
首先使用包管理器控制台安装这些 NuGet 包:
PM> Install-Package Microsoft.AspNet.Identity.Owin
PM> Install-Package Microsoft.AspNet.Identity.EntityFramework
PM> Install-Package Microsoft.Owin.Host.SystemWeb
添加一个用户类和IdentityUser继承:
public class AppUser : IdentityUser
{
//add your custom properties which have not included in IdentityUser before
public string MyExtraProperty { get; set; }
}
为角色做同样的事情:
public class AppRole : IdentityRole
{
public AppRole() : base() { }
public AppRole(string name) : base(name) { }
// extra properties here
}
将您的 DbContext 父级从 DbContext 更改为 IdentityDbContext<AppUser>,如下所示:
public class MyDbContext : IdentityDbContext<AppUser>
{
// Other part of codes still same
// You don't need to add AppUser and AppRole
// since automatically added by inheriting form IdentityDbContext<AppUser>
}
如果您使用相同的连接字符串并启用迁移,EF 将为您创建必要的表。
或者,您可以扩展 UserManager 以添加您想要的配置和自定义:
public class AppUserManager : UserManager<AppUser>
{
public AppUserManager(IUserStore<AppUser> store)
: base(store)
{
}
// this method is called by Owin therefore this is the best place to configure your User Manager
public static AppUserManager Create(
IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
{
var manager = new AppUserManager(
new UserStore<AppUser>(context.Get<MyDbContext>()));
// optionally configure your manager
// ...
return manager;
}
}
由于 Identity 是基于 OWIN 的,所以你也需要配置 OWIN:
将类添加到App_Start 文件夹(或其他任何地方,如果您愿意)。此类由 OWIN 使用。这将是你的创业课程。
namespace MyAppNamespace
{
public class IdentityConfig
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(() => new MyDbContext());
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
app.CreatePerOwinContext<RoleManager<AppRole>>((options, context) =>
new RoleManager<AppRole>(
new RoleStore<AppRole>(context.Get<MyDbContext>())));
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Login"),
});
}
}
}
几乎完成了,只需将这行代码添加到您的web.config 文件中,以便 OWIN 可以找到您的启动类。
<appSettings>
<!-- other setting here -->
<add key="owin:AppStartup" value="MyAppNamespace.IdentityConfig" />
</appSettings>
现在在整个项目中,您可以像使用 VS 已安装的任何新项目一样使用 Identity。以登录操作为例
[HttpPost]
public ActionResult Login(LoginViewModel login)
{
if (ModelState.IsValid)
{
var userManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
var authManager = HttpContext.GetOwinContext().Authentication;
AppUser user = userManager.Find(login.UserName, login.Password);
if (user != null)
{
var ident = userManager.CreateIdentity(user,
DefaultAuthenticationTypes.ApplicationCookie);
//use the instance that has been created.
authManager.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return Redirect(login.ReturnUrl ?? Url.Action("Index", "Home"));
}
}
ModelState.AddModelError("", "Invalid username or password");
return View(login);
}
您可以创建角色并添加到您的用户:
public ActionResult CreateRole(string roleName)
{
var roleManager=HttpContext.GetOwinContext().GetUserManager<RoleManager<AppRole>>();
if (!roleManager.RoleExists(roleName))
roleManager.Create(new AppRole(roleName));
// rest of code
}
您还可以向用户添加角色,如下所示:
UserManager.AddToRole(UserManager.FindByName("username").Id, "roleName");
通过使用Authorize,您可以保护您的操作或控制器:
[Authorize]
public ActionResult MySecretAction() {}
或
[Authorize(Roles = "Admin")]]
public ActionResult MySecretAction() {}
您还可以安装其他软件包并对其进行配置以满足您的要求,例如 Microsoft.Owin.Security.Facebook 或任何您想要的。
注意:不要忘记将相关的命名空间添加到您的文件中:
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
您还可以查看我的其他答案,例如 this 和 this 以了解身份的高级使用。