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;
}
}
Thanks mate….