I try to implement a Custom MembershipPriver with a Custom MemberShipUser in my own database (with a specifics Users Table Model) :
This is ly diffent files :
iTwitterMembershipProvider.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Collections.Specialized;
using iTwitter.Models;
public class iTwitterMembershipProvider : MembershipProvider
{
public override string ApplicationName
{
get { return _ApplicationName; }
set { _ApplicationName = value; }
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
return false;
}
public override iTwitterMembershipUser CreateUser(string login,
string password,
string email,
string tokenKey,
string tokenSecret,
string twitterUserId,
object providerUserKey,
out MembershipCreateStatus status)
{
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(login,
password,
true);
OnValidatingPassword(args);
if (args.Cancel)
{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
{
status = MembershipCreateStatus.DuplicateEmail;
return null;
}
iTwitterMembershipUser u = GetUser(login, false);
if (u == null)
{
UserRepository _user = new UserRepository();
_user.CreateUser(login, password, email);
status = MembershipCreateStatus.Success;
return GetUser(login, false);
}
else
{
status = MembershipCreateStatus.DuplicateUserName;
}
return null;
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new NotImplementedException();
}
public override bool EnablePasswordReset
{
get { return _EnablePasswordReset; }
}
public override bool EnablePasswordRetrieval
{
get { return _EnablePasswordRetrieval; }
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override int GetNumberOfUsersOnline()
{
throw new NotImplementedException();
}
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override iTwitterMembershipUser GetUser(string login, bool userIsOnline)
{
UserRepository _user = new UserRepository();
return _user.GetUser(login);
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new NotImplementedException();
}
public override string GetUserNameByEmail(string email)
{
UserRepository _user = new UserRepository();
return _user.GetUserNameByEmail(email);
}
public override int MaxInvalidPasswordAttempts
{
get { return _MaxInvalidPasswordAttempts; }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { return _MinRequiredNonalphanumericCharacters; }
}
public override int MinRequiredPasswordLength
{
get { return _MinRequiredPasswordLength; }
}
public override int PasswordAttemptWindow
{
get { return _PasswordAttemptWindow; }
}
public override MembershipPasswordFormat PasswordFormat
{
get { return _PasswordFormat; }
}
public override string PasswordStrengthRegularExpression
{
get { return _PasswordStrengthRegularExpression; }
}
public override bool RequiresQuestionAndAnswer
{
get { return _RequiresQuestionAndAnswer; }
}
public override bool RequiresUniqueEmail
{
get { return _RequiresUniqueEmail; }
}
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override bool UnlockUser(string userName)
{
throw new NotImplementedException();
}
public override void UpdateUser(MembershipUser user)
{
throw new NotImplementedException();
}
public override bool ValidateUser(string login, string password)
{
if (login == password)
{
return true;
}
else
{
return false;
}
}
//
// A helper function to retrieve config values from the configuration file.
//
private string GetConfigValue(string configValue, string defaultValue)
{
if (string.IsNullOrEmpty(configValue))
return defaultValue;
return configValue;
}
//
// Properties from web.config, default all to False
//
private string _ApplicationName;
private bool _EnablePasswordReset;
private bool _EnablePasswordRetrieval = false;
private bool _RequiresQuestionAndAnswer = false;
private bool _RequiresUniqueEmail = true;
private int _MaxInvalidPasswordAttempts;
private int _PasswordAttemptWindow;
private int _MinRequiredPasswordLength;
private int _MinRequiredNonalphanumericCharacters;
private string _PasswordStrengthRegularExpression;
private MembershipPasswordFormat _PasswordFormat = MembershipPasswordFormat.Hashed;
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
if (name == null || name.Length == 0)
name = "CustomMembershipProvider";
if (String.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Custom Membership Provider");
}
base.Initialize(name, config);
_ApplicationName = GetConfigValue(config["applicationName"],
System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
_MaxInvalidPasswordAttempts = Convert.ToInt32(
GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
_PasswordAttemptWindow = Convert.ToInt32(
GetConfigValue(config["passwordAttemptWindow"], "10"));
_MinRequiredNonalphanumericCharacters = Convert.ToInt32(
GetConfigValue(config["minRequiredNonalphanumericCharacters"], "1"));
_MinRequiredPasswordLength = Convert.ToInt32(
GetConfigValue(config["minRequiredPasswordLength"], "6"));
_EnablePasswordReset = Convert.ToBoolean(
GetConfigValue(config["enablePasswordReset"], "true"));
_PasswordStrengthRegularExpression = Convert.ToString(
GetConfigValue(config["passwordStrengthRegularExpression"], ""));
}
}
iTwitterMembershipUser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using iTwitter.Models;
namespace iTwitter.Models
{
public class iTwitterMembershipUser : MembershipUser
{
private string _tokenKey;
private string _tokenSecret;
private string _twitterUserId;
private string _login;
private string _email;
private int _providerUserKey;
public string tokenKey
{
get { return _tokenKey; }
set { _tokenKey = value; }
}
public string tokenSecret
{
get { return _tokenSecret; }
set { _tokenSecret = value; }
}
public string twitterUserId
{
get { return _twitterUserId; }
set { _twitterUserId = value; }
}
public string login
{
get { return _login; }
set { _login = value; }
}
public string email
{
get { return _email; }
set { _email = value; }
}
public int providerUserKey
{
get { return _providerUserKey; }
set { _providerUserKey = value; }
}
public iTwitterMembershipUser(object providername,
string login,
int providerUserKey,
string email,
string tokenKey,
string tokenSecret,
string twitterUserId)
{
this.tokenKey = tokenKey;
this.tokenSecret = tokenSecret;
this.twitterUserId = twitterUserId;
this.login = login;
this.providerUserKey = providerUserKey;
this.email = email;
}
}
}
webconfig.cs
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<add name="iTwitterDB" connectionString="metadata=res://*/Models.iTwitter.csdl|res://*/Models.iTwitter.ssdl|res://*/Models.iTwitter.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\iTwitter.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" /></connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear />
<add name="CustomMembershipProvider" type="iTwitterMembershipProvider" connectionStringName="iTwitterDB" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="iTwitterDB" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="iTwitterDB" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
iTwitterDB :
id int
login varchar(50)
password varchar(100) (MD5 Password Hash)
email varchar(100)
tokenKey varchar(100)
tokenSecret varchar(100)
twitterUserId varchar(100)
UserRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace iTwitter.Models
{
public class UserRepository
{
public iTwitterMembershipUser CreateUser(string login, string password, string email)
{
using (iTwitterDB db = new iTwitterDB())
{
Users user = new Users();
user.login = login;
user.email = email;
user.password = password;
user.tokenKey = "0";
user.tokenSecret = "0";
user.twitterUserId = "0";
db.AddToUsers(user);
db.SaveChanges();
return GetUser(login);
}
}
public string GetUserNameByEmail(string email)
{
using (iTwitterDB db = new iTwitterDB())
{
var result = from u in db.Users where (u.email == email) select u;
if (result.Count() != 0)
{
var dbuser = result.FirstOrDefault();
return dbuser.login;
}
else
{
return "";
}
}
}
public iTwitterMembershipUser GetUser(string login)
{
using (iTwitterDB db = new iTwitterDB())
{
var result = from u in db.Users where (u.login == login) select u;
if (result.Count() != 0)
{
var dbuser = result.FirstOrDefault();
string _login = dbuser.login;
int _providerUserKey = dbuser.id;
string _email = dbuser.email;
string _tokenKey = dbuser.tokenKey;
string _tokenSecret = dbuser.tokenSecret;
string _twitterUserId = dbuser.twitterUserId;
iTwitterMembershipUser user = new iTwitterMembershipUser("CustomMembershipProvider",
_login,
_providerUserKey,
_email,
_tokenKey,
_tokenSecret,
_twitterUserId);
return user;
}
else
{
return null;
}
}
}
}
}
I've some error during compilation :
1) 'iTwitterMembershipProvider' does not implement inherited abstract
member 'System.Web.MembershiProvider.CreateUser(string, string, string, string, string, bool, object, out System.Web.Security.MembershipCreateStatus)'
2) iTwitterMembershipProvider.CreateUser(string,
string, string, string, string, bool, object, out System.Web.Security.MembershipCreateStatus)': no suitable method found to override
3)'iTwitterMembershipProvider.GetUser(string,
bool)': return type must be 'System.Web.Security.MembershipUser' to match overridden member 'System.Web.Security.MembershipProvider.GetUser(string, bool)'
I'm blocked here.
Thank you.