首页 文章

MVC 5和ASP.NET身份 - 实现混乱

提问于
浏览
12

我正在创建一个新的Web应用程序,将使用 MVC 5Entity Framework Database First Approach 编写 . 我还想使用 ASP.Net Identity 来照顾会员资格,身份验证,授权等 .

我已经阅读了很多关于网络上的ASP.Net身份以及它是如何工作的,但是,我仍然在学习这个主题 .

当我在Visual Studio 2013中创建我的MVC 5应用程序并查看 Account Controller 时,我的第一直觉是我不喜欢我所看到的,即 DbContext 被引用名为' ApplicationDbContext '. The reason I didn' t这样是因为我更喜欢保留我的DbContext在我的解决方案中的相应项目中,即在我的模型层中遵循 separation of concerns 逻辑 .

此外,开箱即用的MVC 5项目使用Entity Framework Code First创建默认数据库和表来存储用户,角色等 .

因为 I must use an existing database with an existing User table ,这种方法不适合我的需要 .

我仍然希望为我的应用程序使用最新的ASP.Net标识,因为它看起来有很多好处,因此,我发现这篇文章剥离了很多实体框架代码,但仍然将OWIN驱动的身份验证纳入ASP.NET MVC .

http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown-part-deux

使用上面的教程,这是我的 Account ControllerHttpPost 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应用程序中,我通常使用自己的自定义成员身份,当用户登录到站点并进行身份验证时,我会在 FormsAuthenticationTicketUserData 字符串中存储任何其他用户详细信息,例如userID,DOB等 .

由于上面的代码不使用 FormsAuthentication ,而是使用 OWIN CookieAuthentication ,我不知道如何存储这些额外的用户数据 .

因此,我对我遇到的问题有几个问题 .

  • 如何以我在FormsAuthentication中使用的方式存储userID或任何其他用户数据(DOB等)?这是通过向身份添加声明来完成的吗?

  • 考虑到我在现有数据库中使用Entity Framework Database First,上面使用ASP.Net Identity / OWIN的方法是否正确?

  • 我是否应该使用帐户控制器中使用的开箱即用的代码,即UserManager,ApplicationUser,ApplicationDbContext等,并将其连接到我现有的数据库?

如果我的问题令人困惑,我深表歉意 . 我想我只是不确定在我最近的项目中尝试使用ASP.Net Identity时我应该使用什么方法 .

任何反馈将不胜感激 .

谢谢 .

2 回答

  • 4

    1)新的Katana Cookie中间件支持声明 . 这使得这比形成auth cookie更好;声明模型任何键/值对,并且可以存储在身份验证cookie中 . 有关详细信息,请参阅此帖子:

    http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

    2&3)至于您的身份数据存储,如果您需要使用现有的表,那么您可能无法使用Microsoft的EF提供的类 . 相反,您可以自己动手实现IUserStore以及您的应用所需的所有其他商店界面 . 我不确定是否值得更改您用于存储用户数据的内容 .

    请记住,OWIN / Katana部分与身份存储分开 .

  • 2

    Here is the solution

    为了加快速度,您可以将示例应用程序添加到项目中,然后通过修改示例应用程序开始,Samples应用程序包括确认电子邮件,密码恢复,角色管理员和用户角色管理等.NuGet package位于:

    Install-Package Microsoft.AspNet.Identity.Samples -Pre
    

    在此处查看示例应用的完整详细信息:ASP.NET Identity 2.0: Customizing Users and Roles

    使用以下属性控制对控制器或操作的访问

    [Authorize] //Anyone with authorization
    [Authorize(Roles="Administrator")] //Admin role only
    

    检查用户是否在角色中

    HttpContext.User.IsInRole("Administrator")
    UserManager.IsInRole(userID, "Administrator")
    

    获取 Profiles 数据

    // Create manager
     var manager = new UserManager<ApplicationUser>(
        new UserStore<ApplicationUser>(new ApplicationDbContext()))
    
    // Find user
    var user = manager.FindById(User.Identity.GetUserId());
    var profileProperty_1 = user.profileProperty_1
    

相关问题