I've been searching through some examples here, but could not find what I needed, so I'm posting my question here:

I'm using Form authentication and MVC 4.5.

The problem is following:

I'm emailing the URL to the user and the user needs to click on URL and be able to get redirected to that URL after he was authenticated.

My Login Controller has a method Index that is invoked when user tries to log in:

[HttpPost]
public ActionResult Index(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        try
        {
            LoginModel lm = LoginModel.AuthenticateUser(model.UserName, model.Password);
            if (lm.IsAuthenticated)
            {
                ApplicationSession.SetUser(lm.User);
                FormsAuthentication.SetAuthCookie(model.UserName, false);

                if (lm.User.ChangePassword)
                {
                    return Redirect(returnUrl ?? Url.Action("ForceChangePassword", "ChangePassword"));
                }
                else
                {
                    return Redirect(returnUrl ?? Url.Action("Index", "Details"));
                }
            }
            else
            {
                if (lm.GroupPermissionMessage.Length > 0)
                {
                    ModelState.AddModelError("", lm.GroupPermissionMessage);
                }
                else
                {
                    ModelState.AddModelError("", lm.SaveResult.ErrorDescription);
                }

                return View();
            }
        }
        catch(Exception error)
        {
            ModelState.AddModelError("", error.Message);
            return View();
        }
    }
    else
    {
        return View();
    }
}

The login form has the following definition:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "LoginForm", returnUrl = Request.QueryString["ReturnUrl"] }))

This is my logic that generates URL for the email:

 var queryString = @Url.Action("Index", "Details", new System.Web.Routing.RouteValueDictionary(new { id = model.Ticket.TicketId }), "http", Request.Url.Host);
                    var ticketUrl = "<a href='"
                                    + @Url.Action("Index", "Detail", new System.Web.Routing.RouteValueDictionary(new { id = model.Ticket.TicketId, returnUrl = queryString }), "http", Request.Url.Host)
                                    + "'>Go to your ticket</a>";

I'm expecting Request.QueryString["ReturnURL"] to be equal to the URL I'm opening from the email, so I can redirect to it in my Index method of a controller.

Right now, I'm able to navigate to that URL if I'm already authenticated. However, if I'm signed off and try to navigate to that URL, Login page is opened first. Then I need to login and should be automatically get redirected to the URL I clicked in my email.

How can I do that?

What am I missing here?

0

There are 0 best solutions below