Wdrożenie funkcji "Zapamiętaj mnie" w ASP.NET MVC

Próbuję zaimplementować funkcję" Zapamiętaj mnie " do mojego formularza logowania. Używam ASP.NET MVC jako moja aplikacja internetowa. Udało mi się uruchomić pliki cookie, ale nie udało mi się automatycznie zalogować użytkownika na wypadek, gdyby wcześniej zaznaczył pole Zapamiętaj mnie. Wiem, jaki jest problem, ale nie wiem, jak go rozwiązać.

W moim Homecontrolle mam:

private LoginViewModel CheckLoginCookie()
{
    if (!string.IsNullOrEmpty(_appCookies.Email) && !string.IsNullOrEmpty(_appCookies.Password))
    {
        var login = new LoginViewModel
                        {
                            Email = _appCookies.Email,
                            Password = _appCookies.Password
                        };

        return login;
    }
    return null;
}


public ActionResult Index()
{
    var login = CheckLoginCookie();
    if (login != null)
        return RedirectToAction("Login", "User", login);

    var viewModel = new HomeIndexViewModel
                        {
                            IntroText =
                                "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
                            LastMinuteDeals = new List<ItemsIndexViewModel>(),
                            TrustedDeals = new List<ItemsIndexViewModel>()
                        };
    return View(viewModel);
}

A w moim Usercontrolle mam metodę login action:

public ActionResult Login()
{
    return PartialView(new LoginViewModel());
}

[HttpPost]
public ActionResult Login(LoginViewModel dto)
{
    bool flag = false;
    if (ModelState.IsValid)
    {
        if (_userService.AuthenticateUser(dto.Email, dto.Password, false)) {
            var user = _userService.GetUserByEmail(dto.Email);
            var uSession = new UserSession
            {
                ID = user.Id,
                Nickname = user.Nickname
            };
            SessionManager.RegisterSession(SessionKeys.User, uSession);
            flag = true;

            if(dto.RememberMe)
            {
                _appCookies.Email = dto.Email;
                _appCookies.Password = dto.Password;
            }
        }
    }
    if (flag)
        return RedirectToAction("Index", "Home");
    else
    {
        ViewData.Add("InvalidLogin", "The login info you provided were incorrect.");
        return View(dto);
    }
}

Więc zasadniczo, co ja myślałem, że zrobiłbym to przekierowanie użytkownika z wyniku akcji Index na kontrolerze domowym w przypadku, gdy był plik cookie logowania. Ale problem polega na tym, że RedirectToAction uruchomi metodę GET Login action, a nie POST, który zajmuje się logowaniem użytkownika.

Czy całkowicie się mylę? A może jest jakiś sposób na wywołanie metody logowania POST używając RedirectToAction lub w inny sposób?
Author: Barney, 2011-04-11

1 answers

Po pierwsze, nigdy nie należy przechowywać poświadczeń użytkownika w pliku cookie. Jest niesamowicie niepewna. Hasło będzie przekazywane przy każdym żądaniu, a także będzie przechowywane w postaci zwykłego tekstu na komputerze użytkownika.

Po drugie, nie odkrywaj koła na nowo, zwłaszcza gdy chodzi o bezpieczeństwo, nigdy nie zrozumiesz tego dobrze.

ASP.Net już zapewnia tę funkcjonalność bezpiecznie z formularzy Authentication i dostawców członkostwa. Powinieneś się temu przyjrzeć. Tworzenie domyślnego MVC projekt będzie zawierał podstawową konfigurację uwierzytelniania. Oficjalna strona MVC ma więcej.

Update

Nadal można używać uwierzytelniania formularzy. Net bez implementacji dostawcy członkostwa. Na poziomie podstawowym działałoby to w ten sposób.

Włączasz uwierzytelnianie formularzy w swojej sieci.config

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

Możesz ozdobić akcje lub kontrolery, które chcesz zabezpieczyć atrybutem [Authorize].

[Authorize]
public ViewResult Index() {
  //you action logic here
}

Następnie utwórz podstawową akcję logowania

[HttpPost]
public ActionResult Login(LoginViewModel dto) {

  //you authorisation logic here
  if (userAutherised) {
    //create the authentication ticket
    var authTicket = new FormsAuthenticationTicket(
      1,
      userId,  //user id
      DateTime.Now,
      DateTime.Now.AddMinutes(20),  // expiry
      rememberMe,  //true to remember
      "", //roles 
      "/"
    );

    //encrypt the ticket and add it to a cookie
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,   FormsAuthentication.Encrypt(authTicket));
    Response.Cookies.Add(cookie);

    return RedirectToAction("Index");

  }

}
 50
Author: David Glenn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 11:28:23