ASP.NET MembershipProvider for Web.config

I had dinner with IanG, Fritz, Si and Kev. We had the obligatory tech-talk in between and thought about useful custom provider for ASP.NET – at some point Fritz came up with the idea of a MembershipProvider which reads from the good old web.config <credentials> element. That sounded like fun – so here it is (full sample here):

public class WebConfigMembershipProvider : MembershipProvider

{

  private FormsAuthenticationUserCollection _users = null;

  private FormsAuthPasswordFormat _passwordFormat;

 

  // not implemented members omitted

 

  public override void Initialize(string name, 
    System.Collections.Specialized.
NameValueCollection config)

  {

    base.Initialize(name, config);

    _passwordFormat = getPasswordFormat();

  }

 

  public override bool ValidateUser(string username, string password)

  {

    try

    {

      if (_passwordFormat == FormsAuthPasswordFormat.Clear)

      {

        if (getUsers()[username].Password == password)

        {

          new AuthenticationSuccessEvent(username, this).Raise();

          return true;

        }

      }

      else

      {

        if (getUsers()[username].Password ==
          FormsAuthentication
.HashPasswordForStoringInConfigFile(password,
            _passwordFormat.ToString()))

        {

          new AuthenticationSuccessEvent(username, this).Raise();

          return true;

        }

      }

    }

    catch

    {

      new AuthenticationFailureEvent(username, this).Raise();

    }

 

    return false;

  }

 

  protected FormsAuthenticationUserCollection getUsers()

  {

    if (_users == null)

    {

      AuthenticationSection section = getAuthenticationSection();

      FormsAuthenticationCredentials creds = section.Forms.Credentials;

      _users = section.Forms.Credentials.Users;

    }

    return _users;

  }

 

  protected AuthenticationSection getAuthenticationSection()

  {

    Configuration config = WebConfigurationManager.OpenWebConfiguration(“~”);

    return (AuthenticationSection)config.GetSection
      (
“system.web/authentication”);

  }

 

  protected FormsAuthPasswordFormat getPasswordFormat()

  {

    return getAuthenticationSection().Forms.Credentials.PasswordFormat;

  }

}

 

 

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to ASP.NET MembershipProvider for Web.config

  1. Rasika says:

    Thanks mate….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s