用现有数据库进行用户认证

时间:2014-03-30 15:06:23

标签: c# entity-framework visual-studio-2013 asp.net-mvc-5 asp.net-identity

我有一个包含这些表的表account的现有数据库:(int)USERIDEMAILPASSWORD。列数较多,但对于此问题并不重要。密码使用BCrypt进行哈希处理。此项目中的class Account也有一个property Role,稍后会迁移到数据库。

我有一个工作的ASP.NET项目,已经可以使用帐户并具有一些功能。现在我想实现用户登录。

我从编辑AccountController开始。我删除了很大一部分因为用户无法在此网站上注册(之前创建了帐户),而且我不想要外部登录支持。

[Authorize]
public class AccountController : Controller
{
    private DbSet<Account> accounts; // will become a repo later

    public AccountController()
    {
        this.accounts = new MyContext().Accounts;
    }

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel model, string returnUrl)
    {

        if (ModelState.IsValid && ValidateLogin(model)) 
        {
            string role = "Student"; // will be saved in Account and DB later
            FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMonths(3), model.RememberMe, role, "/");

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authenticationTicket));
            Response.Cookies.Add(cookie);
            HttpContext.User = new GenericPrincipal(new GenericIdentity(model.UserName), new string[] {"role"});
            return RedirectToAction("Index", "Home");
        }

        ModelState.AddModelError("", "The username or password is incorrect");
        return View(model);
    }

    private bool ValidateLogin(LoginViewModel model)
    {
        var account = accounts.SingleOrDefault(x=>x.Email == model.UserName);
        return account != null && BCrypt.CheckPassword(model.Password, account.Password);
    }

    //
    // POST: /Account/LogOff
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
       FormsAuthentication.SignOut();
        return RedirectToAction("Index", "Home");
    }
}

此登录检查有效,但似乎不保存cookie,系统也不知道用户已登录。

另外,这是最好的方法吗?也许我最好通过实施Identity来支持MVC 5 IdentityUser框架,但我需要哪些其他接口?我如何支持现有角色?我是否需要与现有IdentityDBContext分开的新DataContext

0 个答案:

没有答案
相关问题