1

我想在 MVC 4 代码优先应用程序中使用我的自定义用户表。我在我的数据库上下文中定义了高级用户表:

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

模型如下:

 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; }
        ...
    }

当应用程序启动时,它会调用:

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

在控制器中,我使用Add(entity)来保存用户实体。保存后我想登录用户。但它不起作用:

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

保存用户后,数据保存在我的数据库中,但无法登录,我该怎么办?

编辑:

用我的业务方法保存用户实体是否正确?或者我必须只用 WebSecurity.CreateUserAndAccount() 来做?

如果我可以使用自己的保存方法,如何将密码保存在数据库中?

4

1 回答 1

4

您可以直接使用表单身份验证。

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

这是一个可以帮助您解决密码问题的用户类。它依赖于 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);
        }
    }
于 2013-01-08T14:42:31.227 回答