Having different login pages for different ASP.NET MVC 3 areas

Can I have different login URL for different ASP .NET MVC3 areas?

e.g. I would like to have different login page for Administrator and Data entry operators.

I see a web.config in each area’s view portion and I have tried doing:

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

but it does not play well.

Cheers.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I’m not aware of .NET handling this for you but you could create a custom AuthorizationAttribute

public class CustomAuthorization : AuthorizeAttribute {

  public string Url { get; set; }

  public override void OnAuthorization(AuthorizationContext filterContext) {

    if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
      filterContext.HttpContext.Response.Redirect(Url);
    }
    base.OnAuthorization(filterContext);

  }

}

An add that to your controllers/actions

[CustomAuthorization(Url="/Area/Login")]
public class HomeController {
  //...
}

Method 2

My solution was based on the solution presented by David Glenn, thanks.

public class CustomAuthorization : AuthorizeAttribute
{
    public string Url { get; set; }

    // redirect to login page with the original url as parameter.
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery);
    }
}

And add the Attribute to your controllers/actions

[CustomAuthorization(Url="/Area/Login")]
public class HomeController {
  //...
}

Is better use filterContext.Result than filterContext.HttpContext.Response.Redirect(Url) to redirect because the current filter will redirect immediately to the login page otherwise the original action will be called and only then redirected to login page.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x