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
}
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>
}
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;
}
}
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>
现在,在整个项目中,您可以使用Identity,就像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
}
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;
USE ["YourDatabse"]
GO
/****** Object: Table [dbo].[AspNetRoles] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetRoles](
[Id] [nvarchar](128) NOT NULL,
[Name] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserClaims] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserClaims](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserLogins] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserLogins](
[LoginProvider] [nvarchar](128) NOT NULL,
[ProviderKey] [nvarchar](128) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED
(
[LoginProvider] ASC,
[ProviderKey] ASC,
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserRoles] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserRoles](
[UserId] [nvarchar](128) NOT NULL,
[RoleId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUsers] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUsers](
[Id] [nvarchar](128) NOT NULL,
[Email] [nvarchar](256) NULL,
[EmailConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](max) NULL,
[SecurityStamp] [nvarchar](max) NULL,
[PhoneNumber] [nvarchar](max) NULL,
[PhoneNumberConfirmed] [bit] NOT NULL,
[TwoFactorEnabled] [bit] NOT NULL,
[LockoutEndDateUtc] [datetime] NULL,
[LockoutEnabled] [bit] NOT NULL,
[AccessFailedCount] [int] NOT NULL,
[UserName] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[AspNetUserClaims] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[AspNetUserLogins] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[AspNetUserRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[AspNetRoles] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
GO
ALTER TABLE [dbo].[AspNetUserRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
GO
4条答案
按热度按时间2jcobegt1#
为您现有的项目配置标识并不困难。您必须安装一些NuGet包并进行一些小的配置。
首先使用Package Manager Console安装以下NuGet软件包:
添加一个用户类并使用
IdentityUser
继承:对角色执行相同操作:
将
DbContext
父项从DbContext
更改为IdentityDbContext<AppUser>
,如下所示:如果使用相同的连接字符串并启用迁移,EF将为您创建必要的表。
或者,您可以扩展
UserManager
以添加所需的配置和定制:由于身份基于OWIN,因此您还需要配置OWIN:
添加一个类到
App_Start
文件夹(或者其他任何地方,如果你愿意的话)。这个类由OWIN使用。这将是你的启动类。只需将这行代码添加到您的
web.config
文件中,这样OWIN就可以找到您的启动类。现在,在整个项目中,您可以使用Identity,就像VS已经安装任何新项目一样
您可以创建角色并将其添加到用户中:
您还可以为用户添加角色,如下所示:
通过使用
Authorize
,您可以保护您的操作或控制器:或
您也可以安装额外的软件包,并配置它们以满足您的要求,如
Microsoft.Owin.Security.Facebook
或任何您想要的。**注意:**不要忘记将相关的命名空间添加到文件中:
您还可以查看我的其他答案,如以下内容和高级使用标识的内容。
yi0zb3m42#
这就是我将Identity与现有数据库集成所做的工作。
1.使用MVC模板创建一个示例MVC项目。该项目包含标识实现所需的所有代码- Startup.Auth.cs、IdentityConfig.cs、帐户控制器代码、管理控制器、模型和相关视图。
1.为Identity和OWIN安装必要的nuget包。
1.将所有这些代码复制到现有项目中。请注意,不要忘记为标识添加“DefaultConnection”连接字符串以Map到数据库。请检查IdentityModel.cs中的ApplicationDBContext类,在其中可以找到对“DefaultConnection”连接字符串的引用。
1.这是我在现有数据库上运行的SQL脚本,用于创建必要的表:
1.检查并解决任何剩余的错误,你就完成了。身份将处理其余的:)
xxslljrj3#
我推荐IdentityServer。这是一个.NET Foundation项目,涵盖了许多关于身份验证和授权的问题。
概述
IdentityServer是一个基于.NET/Katana的框架和可托管组件,允许使用OpenID Connect和OAuth2等协议为现代Web应用程序和API实施单点登录和访问控制。它支持广泛的客户端,如移动的、Web、SPA和桌面应用程序,并且可扩展以允许在新的和现有的架构中集成。
有关更多信息,例如
请查看documentation和demo。
6g8kf2rb4#
好吧,我知道我可能太迟了。这是为那些已经做过一次或多次迁移的人准备的。那些项目工作得很好的人,那些在数据库中有AspNet表,但没有与之相关的控制器、模型和视图的人。
我也遇到了同样的问题。我开始我的项目时没有激活认证。然后我意识到我没有认证的所有元素(Account和Manage在Views文件夹中,accountController和ManageController在控制器中,AccountViewModel和ManageViewModel在模型中)。我刚刚创建了其他具有类似设置的项目,然后,我设法将丢失的文件复制到我的初始项目中。在那之后,我检查了每一个步骤,以更改名称空间并导入到我的项目的名称空间中