Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect a user back to where he was after login in asp.net mvc 3

I'm learning ASP.NET MVC3 and I'm now examining the user handling. My first problem would be (I know there is a lot about this subject in other threads, I just fail to find a good one with MVC3) that I want the login page to redirect me where I came from, or where I was redirected from. In php perhaps I would add this url to the querystring, maybe. But I need a way to do this somehow automatically, and this is a so common design pattern I was wondering if there is a "built in" way to do this.

What would be the cleanest, or preferred way to do this?

Also when I'm redirecting to a login page which would be the best way for checking and storing the url which I'm redirected from? I would check for the referrer in the request object and spit it out in the url as "?redirect=protected.html" but I'm not even sure how to properly do this.

Any advice on this subject would be appreciated.

like image 895
vinczemarton Avatar asked Jan 21 '23 05:01

vinczemarton


1 Answers

MVC works the same way as ASP.NET.

If you use Forms Authentication a lot of those questions will be answered for you.

In your Web Config find the line that says authentication="Windows" and then change that to Forms

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" />
</authentication>

MVC 3 will actually give you the Account/LogOn route as part of the MVC 3 template project (check your models and see if you have one called AccountModel).

Then you just add Authorization to deny all users to your site:

<authorization>
  <deny users="?"/>
</authorization>

by default this will send any person coming to your site off to your login.

So after you have validated that there login credentials are correct you set the AuthCookie the same as ASP.NET:

FormsAuthentication.SetAuthCookie(userName, false);

Form this you can the redirect to where ever you want.

to redirect back to where you came from use:

FormsAuthentication.RedirectFromLoginPage(userName, false);

Not forgetting the other useful statement of:

FormsAuthentication.SignOut();

Without Authentication the site wont let you access anywhere until you are logged in, so the CSS will stop working.

The locations I have added to make sure this doesnt happen are as follows:

<location path="Content">
 <system.web>
  <authorization>
    <allow users="?"/>
  </authorization>
 </system.web>
</location>
<location path="Scripts">
 <system.web>
  <authorization>
    <allow users="?"/>
  </authorization>
 </system.web>
</location>
like image 164
Luke Duddridge Avatar answered Jan 29 '23 16:01

Luke Duddridge