更新时间:2023-02-17 07:48:51
配置标识,以现有的项目也不是很难的事情。您必须安装一些的NuGet包,并做一些小的配置。
Configuring Identity to your existing project is not hard thing. You must install some NuGet package and do some small configuration.
首先,在包管理器控制台安装这些包的NuGet:
First install these NuGet packages in Package Manager Console:
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; }
}
做同样的事情角色:
Do same thing for role:
public class AppRole : IdentityRole
{
public AppRole() : base() { }
public AppRole(string name) : base(name) { }
// extra properties here
}
您的DbContext
父窗体修改的DbContext
到 IdentityDbContext< APPUSER>
是这样的:
Change your DbContext
parent form DbContext
to IdentityDbContext<AppUser>
like this:
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创建必要的表给你。
If you use same connection string and enabled migration EF create necessary tables for you.
(可选),你可以多大程度上的UserManager
添加所需的配置和定制:
Optionally you could extent UserManager
to add your desired configuration and customization:
public class AppUserManager : UserManager<AppUser>
{
public AppUserManager(IUserStore<AppUser> store)
: base(store)
{
}
// this method is called by Owin therefore 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;
}
}
由于身份是基于OWIN需要配置OWIN太:
Since Identity is based on OWIN you need configure OWIN too:
一类加入 App_Start
文件夹(或其他任何地方,如果你想)。这个类由OWIN
Add a class to App_Start
folder (or anywhere else if you want). This class is used by 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"),
});
}
}
}
几乎刚做这行code添加到您的的web.config
文件,以便OWIN可以找到你的启动类。
Almost done just add this line of code to your web.config
file so OWIN could find your startup class.
<appSettings>
<!-- other setting here -->
<add key="owin:AppStartup" value="MyAppNamespace.IdentityConfig" />
</appSettings>
现在在整个项目中,你可以使用Identity就像新的项目已经通过安装VS.例如,考虑登陆行动
Now in entire project you could use Identity just like new project had already installed by VS. Consider login action for example
[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);
AuthManager.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return Redirect(login.ReturnUrl ?? Url.Action("Index", "Home"));
}
}
ModelState.AddModelError("", "Invalid username or password");
return View(login);
}
您可以使角色和添加到您的用户:
You could make roles and add to your users:
public ActionResult CreateRole(string roleName)
{
var roleManager=HttpContext.GetOwinContext().GetUserManager<RoleManager<AppRole>>();
if (!roleManager.RoleExists(roleName))
roleManager.Create(new AppRole(roleName));
// rest of code
}
您可以添加任何作用,这样任何用户:
You could add any role to any user like this:
UserManager.AddToRole(UserManager.FindByName("username").Id, "roleName");
通过使用授权
,你可以保护你的动作和控制器:
By using Authorize
you could guard your actions or controllers:
[Authorize]
public ActionResult MySecretAction() {}
或
[Authorize(Roles = "Admin")]]
public ActionResult MySecretAction() {}
另外,你可以安装额外的包,并将其配置,以满足像 Microsoft.Owin.Security.Facebook
或任何你想你的要求。
Also you could install additional package and configure them to meet your requirement like Microsoft.Owin.Security.Facebook
or whichever you want.
注意:不要忘记添加相关的命名空间到您的文件:
Note: Don't forget add relevant namespaces to your files:
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对于高级用途身份。
You could also see my other answers like this and this for advanced use of Identity.