ASP.NET Authentication – Multiple Domains w/ Same Application


In our series about ASP.NET authentication so far we’ve covered all the rather normal cases where you’d want to have the ability to log into different domains attached to the same application.  There are a few additional hurdles you’ll need to overcome to make this work correctly.

The first is, how do I let each domain have its own unique set of logins?

You see, while you can use the same database for multiple domains spread across different applications, the usernames are application specific so that if you log in with and both pointing to the same domain, either will work.  Normally, this is what we want to have happen.

But if those two domains really represent two different web sites and we are just using the same core code, things get a little trickier.

The easiest way to deal with this problem is to make the usernames unique prior to registering and prior to authenticating.  This will mean you’ll need to trap some events.

To create a new user and make the username unique, trap the CreatingUser event on the new user wizard.

At this point, there are a couple choices.  You can just change the username.  I suggest pre-pending the username with the domain.  Or you can call the registration APIs directly.

To change the username use this code.

m_createUserWizard.UserName =
    "domain.com_" + m_createUserWizard.UserName;

If you want to just call the APIs, you’ll want to call CreateUser();

MembershipCreateStatus status;
    true,out status);
e.Cancel = true;
if (status == MembershipCreateStatus.Success)
     e.Cancel = true;
    // display errors.

To login you’ll need to trap the LoggingIn event and the LoginError event.

In the LoggingIn event, change the username

m_login.UserName = "domain.com_" + m_login.UserName;

In the LoginError, you’ll want to change it back so that it displays correctly if there is an error.

m_login.UserName = m_login.UserName
    .Replace("domain.com_", string.Empty);

or something equally as effective.

Related Post

3 Responses to “ASP.NET Authentication – Multiple Domains w/ Same Application”

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail