我在网上看到过很多类似的页面,但它们中的大多数都使用新项目而不是现有项目,或者没有必要的功能。因此,我有一个现有的MVC 5
项目,希望将ASP.NET MVC5身份与登录、电子邮件确认和密码重置功能集成在一起。
除此之外,我还需要在数据库上创建所有必需的表,即用户、角色、组等(我首先在项目中使用EF代码)。是否有与这些需求相对应的文章或样本?
发布于 2015-08-12 19:24:33
为你现有的项目配置身份并不难。您必须安装一些NuGet包并进行一些小的配置。
首先使用包管理器控制台安装这些NuGet包:
PM> Install-Package Microsoft.AspNet.Identity.Owin
PM> Install-Package Microsoft.AspNet.Identity.EntityFramework
PM> Install-Package Microsoft.Owin.Host.SystemWeb
添加一个具有IdentityUser
继承的user类:
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;
}
}
由于身份是基于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安装的任何新项目一样使用标识。考虑登录操作,例如
[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;
发布于 2015-08-18 15:53:20
这就是我将Identity与现有数据库集成在一起的方法。
发布于 2016-08-02 03:04:21
我推荐IdentityServer.This是一个.NET Foundation项目,它涵盖了许多关于身份验证和授权的问题。
概述
IdentityServer是一个基于.NET/Katana的框架和可托管组件,允许使用OpenID连接和OAuth2等协议实现现代web应用程序和API的单点登录和访问控制。它支持广泛的客户端,如移动、web、SPA和桌面应用程序,并且可扩展以允许集成到新的和现有的架构中。
有关更多信息,例如
persistence
https://stackoverflow.com/questions/31960433
复制相似问题