Pergunta

I'm having an issue where redirecting to a secured action after setting a custom forms authentication ticket. Here's what is happening:

  1. I navigate to Site/Home/Index
  2. I'm automatically redirected to Site/Account/Login
  3. I login with a valid user/pass
  4. The RedirecToUrl() function attempts to redirect me back to Site/Home/Index, yet I'm automatically returned back to Site/Account/Login
  5. The request IS authenticated. If I manually navigate to Site/Home/Index, I'm allowed in.

Can anybody shed any light?

My HomeController:

[Authorize]
public ActionResult Index()
{
    return View();
}

My AccountController:

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

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            bool bLogin = MyAuthentication.Login(model.UserName, model.Password);

            if (bLogin)
            {
                Response.Cookies.Add(MyAuthentication.GetAuthenticationCookie(model.UserName.ToLower(), model.RememberMe));
                RedirectToUrl(returnUrl);
            }
            else
                ModelState.AddModelError("", "That is not a valid Username/Password combination");

        }

        return View(model);
    }

    private ActionResult RedirectToUrl(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
            return Redirect(returnUrl);
        else
            return RedirectToAction("Index", "Home");
    }

Here is how I create the custom ticket (just adding userdata):

    public static HttpCookie GetAuthenticationCookie(string UserName, bool persistLogin)
    {
        var userData = null; // Code removed for brevity

        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                 1,
                 UserName,
                 DateTime.Now,
                 DateTime.Now.AddMinutes(20),
                 persistLogin,
                 userData);

        string encTicket = FormsAuthentication.Encrypt(authTicket);
        return new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
    }
Foi útil?

Solução

Ugh!!!

 RedirectToUrl(returnUrl);

Needs to be

 return RedirectToUrl(returnUrl);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top