Tag Archives: authentication

Using two Membership Providers for ASP.NET logins

I quite like the Microsoft Membership Framework for handling membership roles, authentication, and security resources in ASP.NET applications. It’s easy to create the initial user login and management framework for a new application, then swap in a more sophisticated Provider as needed.

For my current project, we have a new requirement to allow logins against multiple user stores. The existing application validates against an Active Directory store. But for a subset of users, there is a need to check if they are in a SQL Server database and allow them to login while they wait for their Active Directory setup to complete. This SQL Server also contains a secondary set of roles that will be relevant for any user that is in the SQL Server user store, regardless of whether they were validated via AD or the SQL Server.

The first step I took was to figure out the easiest way to have two separate providers to validate the user. You can configure as many membership providers as you want in the web.config for your application, but you choose a default provider as part of the setup. If you use the standard Login control, it will only check against that default provider.

In order to change that behavior, I overrode the Login.Authenticate event for my Login control. The method looks a little like this:

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        bool foundUser = false;
        List<string> roles = new List<string>();
        roles.Add("GeneralUser");
        // this will call the default MembershipProvider
        if (Membership.Provider.ValidateUser(LoginBox.UserName, LoginBox.Password))
        {
            foundUser = true;
            // do any additional lookups for this type of user (Default MembershipProvider) here
        } // otherwise, explicitly call secondary provider
        else if (
            Membership.Providers["SecondarySqlMembershipProvider"].ValidateUser(LoginBox.UserName,
                                                                                LoginBox.Password))
        {
            foundUser = true;
            roles.Add("SecondaryUser");
            // do any additional lookups relevant to this type of user
        }
        if (foundUser)
        {
            Session["UserId"] = LoginBox.UserName;
            Session["Groups"] = roles;
        }
        e.Authenticated = foundUser;
    }

I didn’t need to modify the Authentication Ticket or cookie, so I could rely on the Membership Framework to handle the rest. If I need to add additional information, I can do it in the commented spots to correctly handle the type of user I care about.