对数据库验证ASP.NET MVC 5

时间:2015-12-30 10:22:54

标签: c# authentication asp.net-mvc-5

我是ASP NET MVC authentication的新手,我在我的网站项目中遇到了麻烦

默认情况下(作为项目生成的结果),AccountController有一个Login方法

[Authorize]
public class AccountController : Controller
{
    private UserService _userService;
    public UserService UserService{
        get { return _userService ?? (_userService = new UserService()); }
    }

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

        //the line with SignInManager is Default in project
        //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

        //I have implemented my User service which checks in DB is there exists such a user with email and password and returns the same SignInStatus
        var result = UserService.Authenticate(model.Email, model.Password);

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

我的UserService实施:

public class UserService : IUserService
{
    public SignInStatus Authenticate(string email, string password)
    {
        if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
        {
            return SignInStatus.Failure;
        }

        //TODO: perform authentication against DB account
        if (email == "mymail@mail.com" && password == "123")
        {
            return SignInStatus.Success;
        }
        else
        {
            return SignInStatus.Failure;
        }
    }
}

我在[Authorize]

上使用AdministrationController属性
public class AdministrationController : Controller
{
    // GET: Admin/Admin
    [Authorize]
    public ActionResult Index()
    {
        return View();
    }
}

当我进入我的网站的管理区域时,通过http://localhost:53194/administration它不需要任何身份验证(不显示登录屏幕)

如果我在方法

上设置属性[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
    // GET: Admin/Admin
    [Authorize(Roles = "Administrator")]
    public ActionResult Index()
    {
        return View();
    }
}
出现

登录屏幕。 我设置了电子邮件密码。按登录按钮,它会从Login输入AccountController方法,输入SignInStatus.Success

的案例

登录屏幕仍然存在。它未重定向到正常的管理屏幕。

请告诉我如何实施此身份验证。感谢。

1 个答案:

答案 0 :(得分:1)

您似乎在成功登录后设置了身份验证Cookie。因此,用户实际上被重定向到管理页面,但由于他没有有效的身份验证cookie,因此他被重定向回登录表单。

因此请确保设置cookie:

empname