Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 & ASP.NET Identity - Implementation Confusion

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.

like image 405
tcode Avatar asked Jan 27 '14 16:01

tcode


People also ask

What MVC 5?

ASP.NET MVC 5 is a web framework based on Model-View-Controller (MVC) architecture. Developers can build dynamic web applications using ASP.NET MVC framework that enables a clean separation of concerns, fast development, and TDD friendly.

What is the difference between MVC 5 and MVC 6?

While MVC5 can be facilitated in IIS and keeps running on top of The ASP.NET pipeline, MVC 6 can act naturally facilitated and utilizes adaptable pipeline in which we have finish control over the segments that are a piece of the pipeline.

Is ASP.NET MVC 5?

ASP.NET MVC is based on the Model View Controller (MVC) design pattern. The latest version of ASP.NET MVC is version 5.0.

Is MVC 5 a core?

The main difference between ASP.NET Core and ASP.NET MVC 5 is their cross-platform approach. ASP.NET Core can be used on Windows, Mac, or Linux, whereas ASP.NET MVC 5 can only be used for applications on Windows. The ASP.NET Core MVC is a framework for building web apps and APIs, optimized for use with ASP.NET Core.


2 Answers

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.

like image 51
Brock Allen Avatar answered Sep 20 '22 18:09

Brock Allen


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 
like image 42
Moji Avatar answered Sep 22 '22 18:09

Moji