您的位置:首页 > 编程语言 > ASP

自定义ASP.NET MVC身份验证(Identity)信息

2017-08-04 15:19 113 查看

自定义ASP.NET MVC身份验证信息

1.前言

本文为个人第一篇译文,欢迎指出错误。 -

原文:https://blogs.msdn.microsoft.com/webdev/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates/

2.正文

ASP.NET 身份验证(Identity)是ASP.NET应用的新一代身份认证(membership)系统。想要了解更多关于ASP.NET Identity的信息请访问http://blogs.msdn.com/b/webdev/archive/2013/06/27/introducing-asp-net-identity-membership-system-for-asp-net-applications.aspx

ASP.NET Identity的一个主要特点就是能够很方便地增加用户身份信息(profile information)。在已有的ASP.NET Membership系统中,用户和身份信息(profile)被分割到不同的表中,并且通过profile 提供程序(provider)来检索(retrieve)用户信息。这就使得自定义身份信息(profile information)并将其与用户和应用程序数据关联(associate)起来变得很困难。ASP.NET Identity可以很方便地向你的用户添加身份信息(profile information)。

【更新】增加如何存储身份信息到不同的表中的信息

【更新】Rick Anderson 的网站上还有一个关于如何增加安全登录(social logins)的专题。请通过http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on查看

这个章节展示了在VS2013中如何自定义用户身份信息。以下是增加身份信息的步骤:

在VS2013中,新建一个ASP.NET MVC应用

你也可以创建一个Web Forms应用然后使用相同的步骤来增加身份信息

运行应用程序并注册一个用户

你应该注意到在注册页面,程序只要求输入用户名和密码。假设,在注册用户时,你想要再添加一个出生年月作为用户的必填项。

启用Entity Framework的迁移功能(migrations)

建议(recommend)在修改数据库结构(schema)或者更改数据模型(Code first model)时使用迁移功能。ASP.NET Identity使用entity framework 作为基本框架(underlying framework)。更多关于迁移的内容,请访问http://msdn.microsoft.com/en-us/data/jj591621

打开包管理器控制台(package manager console)

输入“Enable-Migrations” 然后 回车



增加你想要添加的身份信息属性

在我们的示例中,我们将要增加一个生日属性

进入 Models\IdentityModels.cs 然后 添加如下属性到 ApplicationUser中。

public class ApplicationUser : IdentityUser { public DateTime BirthDate { get; set; } }


添加
using System;
到文档头部

Add-Migrations修改数据库

由于我们给用户添加了新的属性,所有为了反映这种变化我们需要更新数据库。这是EF迁移真正有用的地方。你可以通过以下步骤来迁移改变数据库

打开包管理器控制台(package manager console)

输入“Add-Migration birthdate” 然后 回车

这会在你的项目中增加一个迁移文档

更新数据库

在包管理器控制台输入“Update-Database” 然后 回车

这个命令会运行所有的迁移文件并且改变数据库结构



数据库效果



修改应用程序来增加BirthDate字段

以下步骤具体(specific)说明了如何向MVC中增加视图,但是你也可以在WebForm中进行相似的视图渲染(render)。

向Models\AccountViewModels.cs的RegisterViewModel 增加 BirthDate

public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "电子邮件")]
public string Email { get; set; }

[Required]
[StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "密码")]
public string Password { get; set; }

[DataType(DataType.Password)]
[Display(Name = "确认密码")]
[Compare("Password", ErrorMessage = "密码和确认密码不匹配。")]
public string ConfirmPassword { get; set; }
#region  custom

public DateTime BirthDate { get; set; }
#endregion
}


更新 Views\Account 的Register.cshtml 视图



更新AccountController.cs中的Register来存储BirthDate

public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email,BirthDate=model.BirthDate };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}

// 如果我们进行到这一步时某个地方出错,则重新显示表单
return View(model);
}


运行应用程序并注册用户。如下所示你将会看到BirthDate



在页面中显示身份信息

当用户登录成功时,你可以通过一下方式显示身份信息

通过身份验证系统(ASP.NET Identity System)获取用户ID

var currentUserId = User.Identity.GetUserId();


通过身份验证系统,实例化用户管理(UserManager)对象

var manager = new UserManager<MyUser>(new UserStore<MyUser>(new MyDbContext()));


获取用户

var currentUser = manager.FindById(User.Identity.GetUserId());


获取具体的身份信息

currentUser.BirthDate


在不同的数据库表中添加身份信息

以上部分展示给你一种简单地在用户表中添加用户身份信息的方法。由于ASP.NET Identity
c1ab
使用了Entity Framework,你可以自定义用户信息。先在假设,你想将身份信息添加到不同的数据库表中。

- 增加一个新的类来存储身份信息

public class MyUser:IdentityUser
{
public virtual MyUserInfo MyUserInfo { get; set; }
}
public class MyUserInfo
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

public class MyDbContext : IdentityDbContext<MyUser>
{
public MyDbContext()
: base("DefaultConnection")
{
}
public System.Data.Entity.DbSet<MyUserInfo> MyUserInfo { get; set; }
}


通过这种方法,运行应用程序你将会在名为MyUserInfo的表中得到FirstName和LastName

- 在页面中显示身份信息

- 当用户登录成功时,你可以通过一下方式显示身份信息

- 通过身份验证系统(ASP.NET Identity System)获取用户ID

var currentUserId = User.Identity.GetUserId();


通过身份验证系统,实例化用户管理(UserManager)对象

var manager = new UserManager<MyUser>(new UserStore<MyUser>(new MyDbContext()));


获取用户

var currentUser = manager.FindById(User.Identity.GetUserId());


获取具体的身份信息

currentUser.MyUserInfo.FirstName


总结

本章讲述了如何自定义用户的身份信息。如果你有任何疑问,请评论或在twitter(@rustd)

译者后记

文章最后将身份信息放到不同表中的方法,我还没有实现。没有查到问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mvc asp.net identity
相关文章推荐