Search code examples
c#asp.net-mvc-4membership-providercustom-authentication

How to add two different login url in form based authentication in C# MVC4?


I have one login page for admin, another login page for general user. I have created a custom membership provider for general user section, now I want to give form authentication in web.config file. How to do that ?


Solution

  • We can not set two login urls for login inside webconfig file.If we create our own custom Membership provider, we have to set it as defaultprovider for making the [Authorize] attribute workable for it. But in my case, there were two providers. Both are custom providers, and I wasn't allowed to change the default provider. One provider is used for Admin login(the default provider), another provider used for user login (custom provider). In web config form authentication was enabled

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

    So, when I was using [Authorize] attribute, it was taking me to the admin login page and it is expected. But I needed an attribute which would take me to user login page. So I created a [AuthorizeUser] attribute which is now taking users to user login section.

    public class AuthorizeUserAttribute : AuthorizeAttribute
    {
    
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var username = filterContext.HttpContext.User.Identity.Name;
            if (username != "")
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new
                RouteValueDictionary(new { controller = "Login", action = "Index" }));
            }
        }
    }
    

    This attribute is taking my users into user login page at ~/login