English 中文(简体)
Membership Provider ChangePassword Method Return Type Problem
原标题:

We have implemented a Custom Membership provider and have a change password control on a webpage that uses this provider. The ChangePassword method in this membership provider class checks some business logic about password strength and validity by connecting to an external webservice. The webservice has the ability to return exactly what is wrong with the new password if any (length problems, special character required etc.).

Now, the signature of the ChangePassword method that has to be overriden by a custom provider is:

public override bool ChangePassword(string username, string oldPassword, string newPassword)

So even though I know the exact problem with the new password the user supplies, I am not able to display it on the webpage because I can only return a true or false from this method and the change password control then takes over and does its own magic depending on the boolean return value. I can hook up the OnChangePasswordError event of the ChangePassword control to show a static error message, or I can even setup the FailureText property of this control to some hard-coded string when an error occurs, but I am unable to provide to the user what exactly is wrong with the password they supplied.

protected void OnPasswordChangeError(object sender, EventArgs e)
        {
            throw new MembershipPasswordException("Tell user what exactly is wrong with the password they supplied");
        }

The MembershipProvider class has a ValidatingPassword event, that is raised BEFORE the password is changed, and I can throw an exception here by checking if the password meets the criteria, but still that exception does not seem to be passed to the ChangePassword control. Here is the code for the ValidatingPassword eventHandler:

void MyMembershipProvider_ValidatingPassword(object sender, ValidatePasswordEventArgs e)
        {
           //if password not valid
           e.Cancel = true;
           e.FailureInformation = new MembershipPasswordException();
           e.FailureInformation;           
        }  

how to send specific information from the ChangePassword method of the Membership provider class to the ChangePassword control to display the correct, non static/hardcoded password change error messages to the user? Is there a way to hook up the ValidatePasswordEventArgs to the EventArgs in the EventHandler for the OnChangePassword method so that I can get the FailureInformation in the ChangePassword control?

From my initial research this does not seem to be possible. Though I feel that the MS team would not have overlooked this and there should be a way.

A few pointers:

MembershipUser.ChangePassword fails without warning http://forums.asp.net/t/983613.aspx

最佳回答

OK, so I finally figured a workaround. It is not the cleanest, but the only one I could come up with or found anywhere that was close to what should have been inclued by default.

Note: I did not have the option to persist this in a database or a cookie.

I created a ChangePasswordNew method that has the same behavior as the MembershipProvider ChangePassword method, but returns string instead of bool. So my new method would look like this:

public string ChangePasswordNew(string username, string oldPassword, string newPassword)
{
    //if password rules met, change password but do not return bool as MembershipProvider method does, 
    //return Success or the exact error for failure instead
    if(passwordChangeRequirementsMet == true)  
    {
        //change the password
        return "success";
    }
    else          
        return "exact reason why password cannot be changed";
}

Now, subscribe to the onPasswordChanging event of the ChangePassword Control:

protected void PasswordIsChanging(object sender, LoginCancelEventArgs e)
{
try
    {
      string response = Provider.ChangePasswordNew(username, currentPass, newPass);
      if(response != "success")
      {
        changePwdCtrl.FailureText = response;
      }
     else
    {
    //cancel call to the default membership provider method that will attempt to
    //change the password again. Instead, replicate the  steps  of AttemptChangePassword(), 
    //an internal method of the ChangePassword control.
    //Performing all the steps instead of calling the method because just calling method
    //does not work for some reason

    e.Cancel = true;
    FormsAuthentication.SetAuthCookie(username, false);
    OnPasswordChanged(sender, e);

    MethodInfo successMethodInfo = changePwdCtrl.GetType().GetMethod("PerformSuccessAction",                                    BindingFlags.NonPublic | BindingFlags.Instance);
    successMethodInfo.Invoke(changePwdCtrl, new object[] { "", "", changePwdCtrl.NewPassword });
}
}
catch(Exception ex)
{
    LogException(ex);
    throw;
}

}

Note: In this case, if there is an error on password change, i.e. response is not "success", the Memebership Provider ChangePassword method will still be called and will return an error again. But I am already setting the FailureText property to the descriptive error returned from response in the first call, which was my objective. I did not mind two method calls in my case. Your case may be different.

Hope this helps someone!

问题回答

You can do this instead, that way you are not calling the changepassword method twice.

if(response != "success") 
      { 
       e.Cancel = true;
((Literal)changePwdCtrl.ChangePasswordTemplateContainer.FindControl("FailureText")).Text = response;
      }

I created a custom membershipprovider class that handles this, the changepassword method in the membership class throws and error message of the specific message and I return that back to the control literal of the change password control.

protected void ChangePassword1_ChangingPassword(object sender, LoginCancelEventArgs e)
    {
        try
        {
            ChangePassword c = (ChangePassword)sender;

            MembershipUser mu = Membership.GetUser(c.UserName);

            bool response;

            try
            {
                response = mu.ChangePassword(c.CurrentPassword, c.NewPassword);
            }
            catch (Exception ex)
            {

                response = false;
                e.Cancel = true;
                //ChangePassword1.ChangePasswordFailureText = ex.Message;
                //ChangePassword1_ChangePasswordError(sender, e);      
                //((Literal)ChangePassword1.ChangePasswordTemplateContainer.FindControl("FailureText")).Visible = true;
                ((Literal)ChangePassword1.ChangePasswordTemplateContainer.FindControl("FailureText")).Text = ex.Message;

            }

            if (response)
            {        
                //cancel call to the default membership provider method that will attempt to 
                //change the password again. Instead, replicate the  steps  of AttemptChangePassword(),  
                //an internal method of the ChangePassword control. 
                //Performing all the steps instead of calling the method because just calling method 
                //does not work for some reason 

                e.Cancel = true;
                FormsAuthentication.SetAuthCookie(c.UserName, false);
                ChangePassword1_ChangedPassword(sender, e);
                MethodInfo successMethodInfo = ChangePassword1.GetType().GetMethod("PerformSuccessAction", BindingFlags.NonPublic | BindingFlags.Instance);
                successMethodInfo.Invoke(ChangePassword1, new object[] { "", "", ChangePassword1.NewPassword });

            }
        }
        catch (Exception ex)
        {            
            throw;
        } 

At one time I needed to pass info out of a provider and ended up just setting a cookie before returning your bool to be picked up on the other end of the call. Worked fine.

I believe a cleaner workaround is for the ChangePassword method to throw an exception. The exception contains the error message!





相关问题
Default Membership and User Profiling vs Custom ones

I was just going through the "AccountController.cs" code (the default one which appears when you create a new ASP.NET MVC project). When I tried to compare it to the one that is proposed in my book, I ...

What is the simplest way to create my own FTP server?

What is the simplest way to create my own FTP server in C#? Some of the folders will be virtual folders. The authentication should be from a SQL Server database, which includes tables of the ASP.NET ...

MembershipProvider in .NET 4.0

How can I add the MembershipProvider class to my .NET 4.0 project in VS 2010 B2? I want to customize a MembershipProvider, but I cannot without adding this class. Please guide me through this process....

ASP.Net Session Not Invalidated After Logout

I have a ASP.Net application in my login page I call FormsAuthentication.SignOut Session.Abandon() Session.Clear() however the Appscan is taking the ASPXAUTH cookie value then after logout is ...

热门标签