Search code examples
asp.net-mvcwebformsasp.net-membership

Change MaxInvalidPasswordAttempts in AspNetMembershipProvider


I want to change the value of MaxInvalidPasswordAttempts based on the user role. For an example :

If user=="Admin" then MaxInvalidPasswordAttempts =1 
If user=="SupervisoR" then MaxInvalidPasswordAttempts =5

I am using the AspNetSqlMembershipProvider.

How do I implement this ?


Solution

  • You can't easily set default MaxInvalidPasswordAttempts by assigning values to that property, since MaxInvalidPasswordAttempts is getter property. To set its value, you need to override that property and includes User.IsInRole method from current context in a custom class derived from SqlMembershipProvider like example below:

    public class CustomMembershipProvider : SqlMembershipProvider
    {
        public override int MaxInvalidPasswordAttempts
        {
            get
            {
                if (HttpContext.Current.User.IsInRole("Admin"))
                {
                    return 1; // example value
                }
                else if (HttpContext.Current.User.IsInRole("Supervisor"))
                {
                    return 5; // example value
                }
    
                // define other roles here
    
                else
                {
                    // use default if no roles provided
                    return base.MaxInvalidPasswordAttempts;
                }
            }
        }
    }
    

    Then in web.config, register fully qualified name of created custom class above (including its namespace) to replace default SqlMembershipProvider:

    <membership ...>
       <providers>
         <add name="SqlProvider" 
              type="YourProjectNamespace.CustomMembershipProvider" ... />
       </providers>
    </membership>