1

I am completely new to ASP.NET MVC and don't know what is what at this point. I have spent many hours trying to figure out what I think should be quite simple and searched the web quite a bit!

I have created an ASP.NET MVC project which prepopulated things such as the Login and Register page.

I got Entity Framework to connect/use my existing DB and wanted to register a user(i.e insert a new user into the DB). Using the code that was pre-populated worked, but inserted into an "internal DB" which is not what I wanted, but using the async await did not work when trying to insert into my existing DB (gave an error in the lines of Model.User can not be converted to Model.DB.User or something along those lines), so I am now doing it synchronously but quite liked the validations it did (i.e checking if user already existed etc., which I have now coded myself).

(sorry for all the typing)

Now I want to log in, and this is the code :

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // This doesn't count login failures towards account lockout
    // To enable password failures to trigger account lockout, change to shouldLockout: true
    var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, isPersistent:false, shouldLockout: false);

    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);

        case SignInStatus.LockedOut:
            return View("Lockout");

        //case SignInStatus.RequiresVerification:
        //    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });

        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
} 

But this fails. I dug a little deeper and its searching in the [AspNetUsers] table? How do I get it to search in MY Employee table in my Existing DB ? I like the validations and based on what I read what async and await does, id like to keep using it.

Ultimately my question is how can I for example get the above code to read from my entity Framework(existing DB) and not from this "internal DB" ?

I hope this makes sense.

Thanks for the help.

EDIT:

Below is the LoginModelView class being used :

public class LoginViewModel
  {
      public string FirstName { get; set; }
      public string Surname { get; set; }

      public string Email { get; set; }

      [Required]
      [Display(Name = "User Name")]
      public string UserName { get; set; }

      [Required]
      [DataType(DataType.Password)]
      [Display(Name = "Password")]
      public string Password { get; set; }
      public DateTime LastLoggedIn { get; set; }
      public bool isLockedOut { get; set; }
      public bool isAuthorized { get; set; }
      public bool isActive { get; set; }
  }

My Employee table consists of the following columns (if this even matters):

PK_UserID, Firstname, Surname, Email, UserName, Password, LastLoggedIn, isLockedOut, isAuthorized, isActive
AxleWack
  • 1,801
  • 1
  • 19
  • 51
  • You are using Model-First EntityFramework which means that as long as you play by the rules, everything is very simple. But as soon as you deviate at all (like using a different/existing db) suddenly things become much more complicated. Can you post what your User model as well as your existing db's User table schema? – nurdyguy May 11 '16 at 15:28
  • I will edit my original post and provide the info. I hope I am passing on the right info. – AxleWack May 11 '16 at 15:30
  • Your table has columns that don't exist on the model. That's why it wont synch. Entity Framework requires that the match perfectly. Try altering your model to match the table schema. – nurdyguy May 11 '16 at 15:37
  • Side note: This is exactly why I don't use Entity Framework. It can be a real pain. I prefer using Dapper (you can import it via nuget) but that is all just personal opinion. – nurdyguy May 11 '16 at 15:38
  • But all I need to Login is the UserName and Password ? Why would any of the other items be needed to log in(Such as the FirstName, surname etc.) ? I went with Entity Framework as I googled which is best route to go with MVC and Entity Framework kept popping up... – AxleWack May 11 '16 at 15:40
  • I understand what you are saying from a process point of view but that's just not how EF works. EF relies on the model exactly matching the db schema. In fact, what EF does is creates the schema based on what the models are. So, in order for it to work it all must match up. EF is very cool in that it is simple to create a project from scratch and be up and running. It is also very cool how it links models using the FKs. But it cost you in terms of flexibility. – nurdyguy May 11 '16 at 15:45
  • Personally I find it a bit silly, but I get what you are saying and understand. I will edit the Model that is being used when tryingi to log in and will get back to you. Thanks for the help, as I said, I am new to MVC and EF, so every little bit is helping me right now. – AxleWack May 11 '16 at 16:00
  • Even after making sure the models match the db, you may have some synch issues. EF can be a real bear about it. If you run into this, post again and I'll see if I can walk you through that. – nurdyguy May 11 '16 at 16:01
  • Meta comment - try removing all the irrelevant stuff and concentrate example and question on EF. – G. Stoynev May 11 '16 at 16:02
  • This is all complicated further by the fact that you're trying to learn both EF and the ASP.NET Identity system at the same time. Getting the ASP.NET Identity system to work with a nonstandard database is quite difficult in itself - to do it while simultaneously learning all the configuration options of EF is probably not a good idea. Start with focusing on your own model and the login stuff as two separate things, and then you can add a user id to your own model and query/insert stuff there based on the UserId only from ASP.NET Identity. – Tomas Aschan May 11 '16 at 16:08
  • 1
    @nurdyguy is wrong. It is not EF that is the problem here. It is ASP.NET Identity. – Stilgar May 11 '16 at 16:08
  • I agree with the ASP.NET Identity being where the problem is as well. I have edited my class(LoginViewModel) which is being used when trying to login, but still getting a failure. I know I am trying to 'Fly' here when I should be walking, but dont have much other choice. Is there any document or site anyone can point me to that can help ? – AxleWack May 11 '16 at 16:23

1 Answers1

1

What you are trying to use is called ASP.NET Identity. It is a framework for user management, authentication, authorization, etc. By default it uses Entity Framework to access a database (will create it if it does not exist) but the specific implementation will require specific tables. You have several choices but I am afraid there is no easy one.

  1. Let ASP.NET Identity create its tables into a new database, script them, put them in your database, change the connection string to point to your database and you have a login system that is in your database. The problem here is that it will NOT use your tables. If your database is new and you can control the design you can change these tables (and the corresponding classes like User) to store the data you want (for example you can add EmployeeNumber to the AspNetUsers table). The downside is that you can't just use your Employee table. You have to accept the predefined tables as part of your model. Now it is debatable if it is a good idea to use the Employee table for login to begin with but still...

  2. This is probably the hardest solution. Implement your own provider for ASP.NET Identity. If you give the identity system a way to do certain operations it will work. However this is a lot of work and you may need a lot of fields from the original tables anyway. Here is more information on implementing providers. I don't think this is a good solution for your case. This is good if you have different storage for your user data not good if you simply dislike the user requirements. Also you will have to write code for many of the checks that you liked.

  3. Do not use ASP.NET Identity. You can use lower level authentication mechanism (in fact ASP.NET Identity uses it) to create a secure encrypted cookie and write your own queries to the database to determine if the user should be logged in successfully. Information on how to use OWIN authentication. In this case you can implement whatever logic you want but you have to do it yourself. No checks performed for you and you have to make sure you hash the passwords properly and so on. You can still use Entity Framework to do those queries to the database. You can write async queries just like the ASP.NET Identity provider does. This is fully supported by EF. If you do not want the identity tables into your database this is probably your best bet.

Sadly none of these is perfect and easy fit for your case.

Stilgar
  • 22,354
  • 14
  • 64
  • 101
  • Thanks Stilgar. This is a new DB so I can change as needed. Id have preferred to not use the tables that are created(Such as AspNetUser), but currently it is just the logging in that is causing a problem and I guess it is not a train smash to use these predefined tables. I have done a check now to check if the Username and password exist : ' if (db.Employees.Where(q => q.UserName.Equals(model.UserName)).Any() && db.Employees.Where(q => q.Password.Equals(model.Password)).Any())' which works fine, but I think I will go with your suggestion in point 1. Thanks for the help! – AxleWack May 11 '16 at 16:41
  • 1
    You can do that but there is much more than these checks that Identity does like password hashing, account lockout (if you need it), password reset, etc. Once you have an User class that derives from IdentityUser you can add whatever other properties (i.e. database columns) you like so in this way you merge ASP.NET Identity with your own requirements. – Stilgar May 11 '16 at 16:46
  • This might be of some help on how to create asp.net Identity tables in your own database - http://stackoverflow.com/questions/28636511/how-to-create-asp-net-identity-tables-inside-existing-database – RBT May 11 '16 at 22:52