1

I would like to use the ValidateUser method of the ActiveDirectoryMembershipProvider to validate that a user exists in AD.

I am taking in the username and password in a form. I would like to then instantiate the provider and call ValidateUser

<add name="AspNetActiveDirectoryMembershipProvider" 
     type="System.Web.Security.ActiveDirectoryMembershipProvider" 
     connectionStringName="ADConnection" 
     attributeMapUsername = "userPrincipalName"  />

I just replace real values with test for the post..

<add name="ADConnection" connectionString="LDAP://test.test.test.com/dc=test,dc=com" />

To do what I want to do, do i need to provide a username and password to the provider so it can connect in first place, i.e. a system account.. and once its established I can then check the user I want to validate?

Thanks, J

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
John
  • 698
  • 1
  • 11
  • 22

1 Answers1

10

With the ASP.NET membership system, the whole point is you don't need to instantiate a provider class or anything - the one you've defined is available right away under the Membership static instance.

So in your case, just make sure the config is correct, and then do something like:

 if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
     FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);
 else
     Msg.Text = "Login failed. Please check your user name and password and try again.";

The Membership will be the necessary class you've defined - just call the static methods on it and be done with it! :-)

Update: it appears you should be able to easily instantiate multiple membership providers along those lines here:

    if (e.UserName.IndexOf("@contoso.com") >= 0)
    {
        e.Authenticated = Membership.Providers["ContosoSqlProvider"].ValidateUser(e.UserName, e.Password);
    }
    else if (e.UserName.IndexOf("@fabrikam.com") >= 0)
    {
        e.Authenticated = Membership.Providers["FabrikamSqlProvider"].ValidateUser(e.UserName, e.Password);
    }
    else
    {
        e.Authenticated = Membership.Provider.ValidateUser(e.UserName, e.Password);
    }

So basically, you can get a specific membership provider by accessing it through Membership.Providers["FabrikamSqlProvider"] and then call methods on it, like .ValidateUser().

The basic Membership.ValidateUser will simply use the membership provider you've defined as the default - but it doesn't stop you from using others!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Thanks, but it is not the only provider I want to use, I want to use the SqlMembershipProvider as well to validate other users against a sql store, so I do need to instantiate it, it can by default pick up the sql one . – John Jan 17 '11 at 12:44
  • @John: updated my answer - I hope I have the solution for your question (unless you've already found it yourself). – marc_s Feb 20 '11 at 09:00