Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does FormsAuthentication.RedirectFromLoginPage() work?

It doesn't return a view. In fact, the Action still needs to return a view after calling this ... so what's going on?

like image 498
ripper234 Avatar asked Jan 02 '10 18:01

ripper234


People also ask

How does form authentication work?

Form Authentication is a token-based system. When users log in, they receive a token with user information that is stored in an encrypted cookie. When a user requests an ASP.NET page via the browser, the ASP.NET verifies whether the form authentication token is available.

How do I redirect a webpage after login?

The most common ways to implement redirection logic after login are: using HTTP Referer header. saving the original request in the session. appending original URL to the redirected login URL.

What is the difference between logic controls and forms authentication?

What is the difference between login controls and Forms authentication? Forms authentication can be easily implemented using login controls without writing any code. Login control performs functions like prompting for user credentials, validating them and issuing authentication just as the FormsAuthentication class.


2 Answers

If you want to use the FormsAuthentication system, you'll want to switch to this line (which implicitly uses the returnUrl parameter).

return Redirect(FormsAuthentication.GetRedirectUrl(model.UserName, true));

You will get the URL that FormsAuthentication.RedirectFromLoginPage would have used, but you will explicitly bail from the action method with a RedirectResult instead.

Note

If you go this route, you'll want to put a defaultUrl parameter in the forms auth web.config line in case someone goes directly to your login page (or they pass in a redirectUrl that doesn't pass FormsAuthentication's security restrictions). Without overriding the default, bad URLs will be redirected to ~/default.aspx. In most MVC apps, that will likely 404.

<forms loginUrl="~/Account/LogOn" defaultUrl="~/" timeout="2880">

Alternative

If you spin up a new MVC 3 sample "Internet Application", you will find a LogOn action method that handles a returnUrl similar to what FormsAuthentication.RedirectFromLoginPage does internally.

if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) {
    return Redirect(returnUrl);
}
else {
    return RedirectToAction("Index", "Home");
}
like image 154
patridge Avatar answered Sep 22 '22 14:09

patridge


It's exactly what it says - a redirect. This is a response code sent to the browser to ask it to request another URL. That's the point at which a view is requested in MVC, or a web page in straight ASP.NET.

like image 35
David M Avatar answered Sep 23 '22 14:09

David M