ログイン認証を担当する次の方法があります。
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel loginModel, string returnUrl)
{
if (ModelState.IsValid)
{
//if (Membership.ValidateUser(loginModel.UserName, loginModel.Password))
var session = RMWebClientBL.Sessions.Login(loginModel.UserName, loginModel.Password);
if(session != null && !session.IsFailed && session.SessionId != Guid.Empty)
{
SetAuthCookie(loginModel, session);
RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View();
}
private void SetAuthCookie(LoginModel loginModel, DomainObjects.Sessions.SessionDetails session)
{
// create encryption cookie
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
loginModel.UserName,
DateTime.Now,
//TODO: make it configurable!!!!
DateTime.Now.AddMinutes(20),
loginModel.RememberMe,
session.SessionId.ToString());
// add cookie to response stream
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if (authTicket.IsPersistent)
{
authCookie.Expires = authTicket.Expiration;
}
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
ただし、ログインしようとすると、「User.Identity.IsAuthenticated」は Cookie を設定した後も false ですが、ロゴをクリックしてホームページにリダイレクトすると認証されているため、ログインしているように見えます。ログイン後にリダイレクトできないのはなぜですか?