1

I want to use my custom User table in MVC 4 code first application. I defined advance User table in my database context:

public class MyDatabase : DbContext
    {
       public DbSet<User> UserSet { get; set; }
       public DbSet<News> NewsSet { get; set; }
       ...
    }

Model is like:

 public class User 
    {
        [Key]
        public int Id{ get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
        ...
    }

When application start, it calls this:

WebSecurity.InitializeDatabaseConnection("MyDatabase", "Users", "Id", "UserName", autoCreateTables: true);

In controller I use Add(entity) to save user entity. After saving I want to log in user. But it does not work:

    [HttpPost]
    public ActionResult Register(User user)
    {
     var result =  MyService.SaveUser(user);
     WebSecurity.Login(result.UserName, result.Password, true);
     return RedirectToAction("Index", "Profile", new { id = result.Id });
    }

After saving user, it's data stored in my database, but it can not log in. How should I do?

Edit:

Is it right to save User entity with my business method? Or I must do it only with WebSecurity.CreateUserAndAccount()?

If I can use my own save method, how to save password in database?

Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90
  • 1
    **DON'T DO THAT**. Don't ever store a password as plain text in the database. Use a salted hash. This is actually quite hard to get right - use the built in membership system instead. – Anders Abel Jan 08 '13 at 10:23
  • If I will store password in database as hashed code, will problem solve? – Jeyhun Rahimov Jan 08 '13 at 10:28
  • 1
    Have a look at this post about security: http://stackoverflow.com/questions/1054022/best-way-to-store-password-in-database and check out http://security.stackexchange.com/ . – Syneryx Jan 08 '13 at 12:13

1 Answers1

4

You could just use forms authentication directly.

 [HttpPost]
    public ActionResult Register(User user)
    {
     var result =  MyService.SaveUser(user);
     SignIn(result.Id, "");
     return RedirectToAction("Index", "Profile", new { id = result.Id });
    }


public void SignIn(string accountId, string roles)
            {
                var authTicket = new FormsAuthenticationTicket(
                    1,
                    accountId,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(20),
                    false,
                    roles
                    );

                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                HttpContext.Current.Response.Cookies.Add(authCookie);
            }

Here is a user class that will help you with password issue. It relies on BCrypt

 public class UserAccount
    {
        public string Id { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }

        public string Password
        {
            get { return PasswordHash; }
            set { PasswordHash = HashPassword(value); }
        }

        public string PasswordHash { get; private set; }

        public List<string> Roles { get; set; }

        public string AuthenticationRoles
        {
            get { return Roles == null ? "" : String.Join(",", Roles.Select(x => x.ToString())); }
        }

        public bool IsActive { get; set; }

        public string Name { get; set; }

        public bool PasswordIsValid(string password)
        {
            bool matches = BCrypt.Net.BCrypt.Verify(password, Password);
            return matches;
        }

        private string HashPassword(string value)
        {
            return BCrypt.Net.BCrypt.HashPassword(value);
        }
    }
Brett Allred
  • 3,459
  • 26
  • 30
  • I use FormsAuthentication first time. It works for me, but how can I get current User's data after sign in with FormsAuthentication? id, roles etc.. – Jeyhun Rahimov Jan 09 '13 at 06:31
  • 1
    HttpContext.Current.User.Identity.Name - This will reads the cookie and returns then name. We are setting the name to the User Id in the forms authentication ticket. From there you can query your database to get additional user data – Brett Allred Jan 09 '13 at 14:03