Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different LoginUrl for different URL's with ASP.NET MVC and Forms Authentication

I have a ASP.NET MVC project, and I would like to have a different LoginUrl for different areas of the website. Depending on the area of the site, different types of credentials are entered.

http://host.com/widget/home should redirect the user to http://host.com/widget/logon.

http://host.com/admin/home should redirect the user to http://host.com/admin/logon.

So far, the best solution I have come up with, is to have Forms Auth loginUrl="~/Account/Logon" in the web.config:

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

In the controller for Account:

public ActionResult LogOn()
{
   //redirect depending on the returnUrl?
   string returnUrl = ControllerContext.Controller.ValueProvider["ReturnUrl"].AttemptedValue;
   if (returnUrl.StartsWith("/widget"))
   {
       return Redirect(string.Format("/widget/Logon?ReturnUrl={0}", returnUrl));
   }
   if (returnUrl.StartsWith("/admin"))
   {
       return Redirect(string.Format("/admin/Logon?ReturnUrl={0}", returnUrl));
   }
   return View();
}

Is there a better way to do this?

like image 779
mlsteeves Avatar asked Aug 25 '09 12:08

mlsteeves


3 Answers

I asked and answered this in my stackoverflow question How to redirect to a dynamic login URL in ASP.NET MVC.

like image 83
Mike Scott Avatar answered Nov 20 '22 06:11

Mike Scott


I know that you can have separate web.config files in sub-folders of a website, so that if you had actual .aspx pages within an admin/ folder, and a web.config in that folder, you could specify the authentication url in that folder separately.

I'm not sure if that works with ASP.NET MVC routes as you're probably not going to have physical files in those sub-folders, but it's worth a try.

like image 41
Deeksy Avatar answered Nov 20 '22 08:11

Deeksy


Add Authenticate attribute to your actions.

Then in global.asax add Application_AuthenticateRequest then look at the sender and redirect there where you want the action to login.

like image 1
user162715 Avatar answered Nov 20 '22 07:11

user162715