MVC 5 & ASP.NET Identity - Implementation Confusio

2019-01-17 12:22发布

I'm creating a new web application that will be written using MVC 5 and Entity Framework Database First Approach. I would also like to use ASP.Net Identity to look after membership, authentication, authorisation etc.

I've read a good bit about the ASP.Net Identity on the web and how it works, however, I am still learning about this topic.

When I created my MVC 5 application in Visual Studio 2013 and looked at the Account Controller my first instinct was that I didn't like what I saw, i.e., a DbContext was being referenced named 'ApplicationDbContext'. The reason I didn't like this was because I prefer to keep my DbContext in the appropriate project within my solution, i.e., in my Model layer which adheres to the separation of concerns logic.

Also, the out of the box MVC 5 project uses Entity Framework Code First to create a default database and tables to store the Users, Roles etc.

Because I must use an existing database with an existing User table, this approach does not suit my needs.

I still want to use the latest ASP.Net Identity for my application as it looks to have many benefits, therefore, I found this article which stripped back alot of the Entity Framework code but still got OWIN powered authentication into an ASP.NET MVC.

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

Using the tutorial above, here is the HttpPost Login method for my Account Controller

    [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);
    }

In my previous MVC applications I usually rolled my own custom membership and when a User logged into the site and was authenticated, I would have stored the any additional user details such as userID, DOB etc in the UserData string of the FormsAuthenticationTicket.

As the code above does not use FormsAuthentication, instead it uses OWIN CookieAuthentication, I am not sure how to store this additional user data.

Therefore, I have a few questions about the problems I am experiencing.

  1. How do I store the userID or any other additional piece of user data (DOB etc) the way I used to in FormsAuthentication? Is this done by adding a Claim to the identity?

  2. Does the method of using ASP.Net Identity/ OWIN above seem correct considering I am using Entity Framework Database First with an existing database?

  3. Should I be using the out of the box code that is used in the Account Controller, i.e., UserManager, ApplicationUser, ApplicationDbContext etc and hooking this up to work with my existing database?

I apologise if my question is confusing, I suppose I'm just a little unsure of what approach I should be using whilst attempting to use ASP.Net Identity in my latest project.

Any feedback would be greatly appreciated.

Thanks.

2条回答
放荡不羁爱自由
2楼-- · 2019-01-17 13:02

1) The new Katana Cookie middleware supports claims. This is what makes this better than forms auth cookie; claims model any key/value pair and those can be stored in the authentication cookie. See this post for more details:

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

2 & 3) As far as your storage for identity data, if you need to work with an existing table then you might not be able to use Microsoft's EF provided classes. Instead you'd be left on your own to implement IUserStore and all the other store interfaces your app needs. I'm not certain it's worth changing what you're already using to store the user data.

Keep in mind that the OWIN/Katana part is separate from the identity storage.

查看更多
Rolldiameter
3楼-- · 2019-01-17 13:12

Here is the solution

To speed things up you can add sample app to your project and start by modifying the sample app, Samples app includes confirmation email, password recovery, roles admin and user role management etc. NuGet package is at:

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

See full details on sample app here: ASP.NET Identity 2.0: Customizing Users and Roles

Controll access to controller or Action by using below attributes

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

Check if user is in role by

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

Get profile data by

// 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 
查看更多
登录 后发表回答