I have an MVC3 site with an admin site and a public facing site. The controllers, views, models etc for these are in the same, single MVC project. They are separated thus: the admin site resides in an MVC3 Area called Admin and the public facing site doesn't belong to an area but exists at the top level. The admin site has a Login view and the public site also has a Login view. In my web.config file I have:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogIn" timeout="2880" />
</authentication>
Now, If I access any page in the public site that requires authentication I get taken to the public site's login page, which is great. However, if I access any page in the admin Area which requires authentication then I again get taken to the public site's login page. The issue then is how do I make sure that if I am on a page in the admin Area that requires authentication that I get sent to the admin login page?
I've faced a similar problem when needing to have a localized login page. I create a custom Authorize attribute:
public class CustomAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectToRouteResult(
new System.Web.Routing.RouteValueDictionary
{
{ "language", filterContext.RouteData.Values[ "language" ] },
{ "controller", "Account" },
{ "action", "LogOn" },
{ "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
}
Just use this attribute instead of the default Authorize attribute. In your case you can check the Request url and depending on that redirect to to the appropriate login page.