0

Scenario:- Suppose user opens link

www.domainname.com/albums/

But to view this page, he should pass through Authentication process. Now in case auth cookies unavailable or session time-out, I redirect him to login page.

But once he authenticates himself,I need to redirect to that page, so how do I capture from which page he landed to login page/

I am using ASP.Net MVC.

Kgn-web
  • 7,047
  • 24
  • 95
  • 161

2 Answers2

2

See this MSDN article to solve your problem: FormsAuthentication.RedirectFromLoginPage Method. And also see this link:

In an ASP.NET MVC project, when you decorate a class or method with [Authorize] and authorization fails, the site automatically redirects to the login page (using the loginUrl specified in web.config). In addition, something in the ASP.NET MVC framework passes along the original request's URL as a ReturnUrl parameter.

You'll have login POST action in your controller something like code below:

CONTROLLER

    [HttpPost]
    [AllowAnonymous]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (User.GetUserInfo() != null)
        {
            return Redirect(Url.Home());
        }

        if (ModelState.IsValid)
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return Redirect(Url.Home());
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }
Community
  • 1
  • 1
melvas
  • 2,346
  • 25
  • 29
  • I have one more thing to check with you..see using `FormAuthentication.SetAuthCookie`, I am setting cookie but now user logins but he doesn't click logout link but simply closes the browser, now in such Cookie doesnt get destroyed but Session expires when he agains comes , Session variables are null, but due to Cookie he is able to login.. **FYI, I am using non-persistent cookie** how should Ihandle this – Kgn-web Aug 29 '15 at 18:17
  • Please, post your comment as a new question and describe there all details. Also, is you get this problem on hosted website or in VS after debug (when you stop debug mode or restart your IIS - session can reset)? – melvas Aug 29 '15 at 19:36
0
public void Login_OnClick(object sender, EventArgs args)

{

if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
      FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);

else

      Msg.Text = "Login failed. Please check your user name and password and try again.";

}
Gabriel
  • 763
  • 1
  • 10
  • 28
Farhan
  • 1