Tuesday, 14 May 2013

Custom membership in mvc

Hello,

This is my first blog.In this blog I am going to show you how to create custom membership.
Step 1:
Put following code under <system.web> in web.config file.

 <membership defaultProvider="MNRMembershipProvider">
      <providers>
        <clear />
        <add connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="3" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="2" passwordAttemptWindow="30" passwordStrengthRegularExpression="" applicationName="/" name="MNRMembershipProvider" type="MNR01.WebUI.Infrastructure.Processors.Membership.CustomMembershipProvider" />
      </providers>
    </membership>

Step 2:

Create a class that will implement Membership.
 public class CustomMembershipProvider : MembershipProvider
    {
}

Step 3:

Override all the methods.

Step 4:

Put following overridden method.
   public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            { throw new ArgumentNullException("config"); }

            if (string.IsNullOrEmpty(name))
            { name = "MNRMembershipProvider"; }

            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "MNR Membership Provider");
            }

            base.Initialize(name, config);
            _maxInvalidPasswordAttempts = Convert.ToInt32(config["maxInvalidPasswordAttempts"]);
            _passwordAttemptWindow = Convert.ToInt32(config["passwordAttemptWindow"]);
            _minRequiredNonAlphaNumericCharacters = Convert.ToInt32(config["minRequiredAlphaNumericCharacters"]);
            _minRequiredPasswordLength = Convert.ToInt32(config["minRequiredPasswordLength"]);
            _passwordStregthRegularExpression = Convert.ToString(config["passwordStrengthRegularExpression"]);
            _enablePasswordReset = Convert.ToBoolean(config["enablePasswordReset"]);
            _enablePasswordRetrieval = Convert.ToBoolean(config["enablePasswordRetrieval"]);
            _requiredQuestionAndAnswer = Convert.ToBoolean(config["requiresQuestionAndAnswer"]);
            _requiredUniqueEmail = Convert.ToBoolean(config["requiresUniqueEmail"]);

            string temp_format = config["passwordFormat"];
            if (temp_format == null)
            {
                temp_format = "Hashed";
            }

            ConnectionStringSettings _connectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

            if (_connectionStringSettings == null || _connectionStringSettings.ConnectionString.Length == 0)
            {
                throw new ProviderException("Connection String Cannot Be Blank.");
            }

            _connectionString = _connectionStringSettings.ConnectionString;

            System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
            var _machinekey = cfg.GetSection("system.web/machineKey") as MachineKeySection;

            if (_machinekey.ValidationKey.Contains("AutoGenerate"))
            {
                if (PasswordFormat != MembershipPasswordFormat.Clear)
                {
                    //throw new ProviderException("Hashed or Encrypted passwords are not supported with auto-generated keys.");
                }
            }
        }

Step 5:

Remove  [InitializeSimpleMembership] attribute from class/method if any.

Step 6:

Call the the method.If we press F12 on the method.It will redirect to metadata but actually our custom method is called because we have overridden membership method.

We can put our custom logic to this overridden method.

Call: System.Web.Security.Membership.ValidateUser(_frmcollection["UserName"], _frmcollection["Password"]);


No comments:

Post a Comment