【发布时间】:2014-02-18 13:41:16
【问题描述】:
我正在创建一个新的 Web 应用程序,它将使用 MVC 5 和 Entity Framework Database First Approach 编写。我还想使用 ASP.Net Identity 来处理成员资格、身份验证、授权等。
我已经阅读了很多关于 Web 上的 ASP.Net Identity 及其工作原理的文章,但是,我仍在学习这个主题。
当我在 Visual Studio 2013 中创建 MVC 5 应用程序并查看 Account Controller 时,我的第一反应是我不喜欢我所看到的,即 DbContext 被命名为“ApplicationDbContext”。我不喜欢这样的原因是因为我更喜欢将我的 DbContext 保留在我的解决方案中的适当项目中,即,在我的模型层中,它遵守关注点分离逻辑。
此外,开箱即用的 MVC 5 项目使用 Entity Framework Code First 创建默认数据库和表来存储用户、角色等。
因为我必须使用现有的数据库和现有的用户表,这种方法不适合我的需要。
我仍然想为我的应用程序使用最新的 ASP.Net Identity,因为它看起来有很多好处,因此,我发现这篇文章剥离了很多实体框架代码,但仍然在 ASP 中获得了 OWIN 支持的身份验证。 NET MVC。
http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown-part-deux
使用上面的教程,这是我的 Account Controller
的 HttpPost Login 方法 [HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
//Calling my own custom Account Service which validates users login details
var user = _AccountService.VerifyPassword(model.UserName, model.Password, false);
if (user)
{
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
//ToDo: Manually adding Role, but will pull from db later
identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
AuthenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent = model.RememberMe
}, identity);
return RedirectToAction("Index", "MyDashboard");
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
在我以前的 MVC 应用程序中,我通常会推出自己的自定义成员资格,当用户登录网站并通过身份验证时,我会将任何其他用户详细信息(例如 userID、DOB 等)存储在 UserData FormsAuthenticationTicket的strong>字符串。
由于上面的代码没有使用FormsAuthentication,而是使用了OWIN CookieAuthentication,我不知道如何存储这些额外的用户数据。
因此,对于我遇到的问题,我有几个问题。
如何像以前在 FormsAuthentication 中那样存储用户 ID 或任何其他用户数据(DOB 等)?这是通过向身份添加声明来完成的吗?
考虑到我将 Entity Framework Database First 与现有数据库一起使用,上述使用 ASP.Net Identity/OWIN 的方法是否正确?
我是否应该使用帐户控制器中使用的开箱即用代码,即 UserManager、ApplicationUser、ApplicationDbContext 等,并将其与我现有的数据库挂钩?
如果我的问题令人困惑,我深表歉意,我想我只是有点不确定在我的最新项目中尝试使用 ASP.Net Identity 时应该使用什么方法。
任何反馈都将不胜感激。
谢谢。
【问题讨论】:
-
嗨@tgriffiths,我和你的情况一样......你能帮我看看你使用的是什么方法吗
标签: asp.net-mvc-5 asp.net-identity owin