none
resetpassword code issue RRS feed

  • Question

  • Hello

    I am in process of creating reserpassword page using adam authentication. I have used CKS retrievepassword code.
    I am calling this page from login.aspx. This page is appearing properly. Whenever I run this page using windows authentication it works correctly and send mail. But whenever I call this page from formbased login, it redirect to me accesdeined.aspx, it is not going submitting page.

    Please review following and let me know whats wrong I am doing here?


    resetpassword.aspx
    <%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Page Language="C#" MasterPageFile="~/_layouts/simple.master" CodeFile="PasswordReset.aspx.cs" Inherits="retrieve_password" AutoEventWireup="true" %>
    <%@ Register tagprefix="WebPartPages" namespace="Microsoft.SharePoint.WebPartPages" assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Assembly Name="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" %>
    
    
    <asp:Content ID="Main" runat="server" contentplaceholderid="PlaceHolderMain" >
    <div>
        <asp:Wizard ID="Wizard1" runat="server" OnNextButtonClick="SendPassword_Click" OnCancelButtonClick="Cancel_Click" DisplayCancelButton="True" DisplaySideBar="False" Height="130px" Width="404px" ActiveStepIndex="0" StartNextButtonText="Send password">
            <WizardSteps>
                <asp:WizardStep ID="WizardStep1" runat="server" Title="Enter UserName" StepType="Start" AllowReturn="False">
                    <table class="ms-input">
                        <tr>
                            <td>
                            <asp:Label ID="Label1" runat="server" Text="Enter your username below and we will send you your password."></asp:Label>
                            <br />
                            <br />
                            <span style="padding-right: 20px;"><asp:Label ID="Label2" runat="server" Text="User name:"></asp:Label></span>
                            <asp:TextBox ID="Username" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator CssClass="ms-error" ID="UserNameRequired" runat="server" ControlToValidate="Username"
                                            ErrorMessage="User Name is required." ToolTip="User Name is required."></asp:RequiredFieldValidator>
                            <asp:CustomValidator CssClass="ms-error" ID="UserNameExists" runat="server" ControlToValidate="Username" 
                                            ErrorMessage="User Name does not exist" OnServerValidate="CheckUserNameExists" />
                           </td>
                         </tr>                                      
                    </table>
                </asp:WizardStep>
                <asp:WizardStep ID="WizardStep2" runat="server" Title="Confirm" StepType="Complete" AllowReturn="False">
                    <table class="ms-input">
                        <tr>
                            <td><asp:Label ID="Label3" runat="server" Text="Your password has been sent to your email address." /></td>
                            <td><asp:Button ID="btnReturn" runat="server" Text="Return to Login" OnClick="ReturnToLogin_Click" /></td>
                        </tr>
                     </table>
                </asp:WizardStep>
            </WizardSteps>
        </asp:Wizard>
        &nbsp;   
    </div>
        &nbsp;   
    </div>
    
    <div style="clear:both;" />
    </asp:Content>
    



    resetpassword.aspx.cs
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    using System.DirectoryServices;
    
    public partial class retrieve_password : System.Web.UI.Page
        {
    	
     
            protected void SendPassword_Click(object sender, EventArgs e)
            {
                Response.Write("not valid yet");
               
                if (Page.IsValid)
                {
                    Response.Write("page is valid");
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        SPWeb web = SPContext.Current.Site.OpenWeb();
    
    
                        // get user
                        //MembershipUser user = Membership.GetUser(Username.Text);
    
                        // TODO: Move email message to settings page
    
                        // email subject
                        string subject = "Requested Information for " + web.Title;
    
                        try
                        {
    
                            const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;
                            const long ADS_OPTION_PASSWORD_METHOD = 7;
                            const int ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0;
                            const int ADS_PASSWORD_ENCODE_CLEAR = 1;
    
                            AuthenticationTypes AuthTypes;  // Authentication flags.
                            int intPort;                    // Port for instance.
                            DirectoryEntry objUser;         // User object.
                            string strPath;                 // Server path.
                            string strPort;                 // Port for instance.
                            string strServer;               // DNS name of the computer with
                            //   the AD LDS installation.
                            string strUser;                 // User DN.
                            string strUserName;
                            strUserName = "testuser";
    
                            // Construct the binding string.
                            strServer = "localhost";
                            strPort = "389";
                            string strAdamSource = System.Configuration.ConfigurationManager.AppSettings["AdamSource"];
                            //strUser = "CN=" + strUserName.ToString().Trim() + ";OU=Users,O=ADAM,C=US"; 
                            strUser = "CN=" + strUserName.ToString().Trim() + strAdamSource.ToString(); 
                            strPath = String.Concat("LDAP://", strServer, ":", strPort, "/", strUser);
                            AuthTypes = AuthenticationTypes.ServerBind;
                            // Bind to user object using LDAP port.
                            try
                            {
                                objUser = new DirectoryEntry(
                                    strPath, strUserName.ToString().Trim(), "password@123", AuthTypes);
                                objUser.RefreshCache();
                            }
                            catch (Exception ex)
                            {
                                if (ex.Message.Contains("unknown user name or bad password"))
                                {
                                    //output.Text = "<br>" +  "<b><font color='#FF0000'>Please enter your correct current password.</font></b>" + "<br><br>"; ;
                                }
                                else
                                {
                                    //output.Text = "<br>" + "<font color='#FF0000'>" + "<b>Error:   Bind failed." + " - " + ex.Message + "</b></font>" + "<br>";
                                }
    
                                return;
                            }
                            // Set port number, method, and password.
                            intPort = Int32.Parse(strPort);
                            try
                            {
                                //  Be aware that, for security, a password should
                                //  not be entered in code, but should be obtained
                                //  from the user interface.
                                objUser.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_PORTNUMBER, intPort });
                                objUser.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_METHOD, ADS_PASSWORD_ENCODE_CLEAR });
                                objUser.Invoke("SetPassword", new object[] { "testuser@123" });
                                objUser.CommitChanges();
                                SPUtility.SendEmail(web, false, false, "testuser@domain.com", "Password is changed for " + strUserName.ToString(), strUserName.ToString()+ " has changed the password. New Password is ");
                            }
                            catch (Exception ex1)
                            {
                                Response.Write( ex1.Message+"<br>");
    
                                return;
                            }
                            //output.Text = "<br>" +  "<b><font color='#0000FF'>Password is changed successfully.</b></font>" + "<br><br>";
                            return;
    
                        }
                        catch (Exception error)
                        {
                            //output.Text = "<br>" + "<b><font color='#FF0000'>User Password Change Error:\n" + error.StackTrace.ToString() + "\n" + error.Message.ToString()+ "</font>"+ "<br>";
                        }
                    
    
    
    
    			// construct message body
                        string body = "You have requested your password from " + web.Title + ".\n\r"; 
                        body += "Your password is: " + "test" + ".\n\r";
                        body += "Thank you";
    
                        // send email
                        SPUtility.SendEmail(web, false, false, "testuser@domain.comt", subject, body);
    
                        web.Dispose();
                    });
                }
            }
    
            protected void Cancel_Click(object sender, EventArgs e)
            {
                // send user to login page            
                SPUtility.Redirect("login.aspx", SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
            }
    
            protected void ReturnToLogin_Click(object sender, EventArgs e)
            {
                // send user to login page
                SPUtility.Redirect("log-in.aspx", SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
            }
    
            protected void CheckUserNameExists(object sender, ServerValidateEventArgs e)
            {
                // see if the user name exists
                //if (Membership.GetUser(Username.Text) == null)
                //    e.IsValid = false;
                //else
                    e.IsValid = true;
            }
        }
    
    
    • Edited by Avian123 Tuesday, May 26, 2009 3:41 PM
    • Edited by Mike Walsh FIN Tuesday, May 26, 2009 4:47 PM "Please help in" removed from Title. Pointless and doesn't describe the problem
    Tuesday, May 26, 2009 3:33 PM

All replies

  • Change this :



    <%@ Register tagprefix="WebPartPages" namespace="Microsoft.SharePoint.WebPartPages" assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>




    To :

    <%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %> 
    let me know if that helps  or you still facing issue
    http://mykbdump.blogspot.com/
    Tuesday, May 26, 2009 4:23 PM
  • Hello

    I made the changes, now it looks like

    <%@ Assembly Name="Microsoft.SharePoint, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Page Language="C#" MasterPageFile="~/_layouts/simple.master" CodeFile="PasswordReset.aspx.cs" Inherits="retrieve_password" AutoEventWireup="true" %>
    <%@ Import Namespace="Microsoft.SharePoint.ApplicationPages"%>
    <%@ Assembly Name="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" %>
    
    
    But it is still redirection to login.aspx page

    Tuesday, May 26, 2009 4:44 PM
  •  okay another thing i just saw  you have added CodeFile and inherits out there  

    Either user inline code or if you want the code to be in code behind follow these steps


    1. Create new empty project in Visual studio and add  your code behind  class in that project

    2. Build the class (strong name it) and place the assembly in GAC ..

    3. Add SafeControl Entry for your assembly in web.config


    4. Open your page in Visual Studio  change

    <%@ Page Language="C#" MasterPageFile="~/_layouts/simple.master" CodeFile="PasswordReset.aspx.cs" Inherits="retrieve...

    To

    <%@ Page language="C#" MasterPageFile="~/_layouts/simple.master"     Inherits="YourNameSpace.yourClassName ,yourAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=keytokenofyourAssembly"   %>




    replace the contents accordingly

    IISreset and there you go ..


    http://mykbdump.blogspot.com/
    Tuesday, May 26, 2009 5:28 PM
  • Hello

    As  you said I created dll and put in GAC folder and did followings, but still no luck, any other idea. It seems somehow I have to use Annonymouse in password.aspx page. I also reset th IIS. Let me know If I did any thing wrong.

    1. added in password.aspx

    <%

    @ Page language="C#" MasterPageFile="~/_layouts/simple.master" Inherits="retrieve_password ,mypwd, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0d3777c01f5dde2b" %>

     

    Here is my class code 

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    using System.DirectoryServices;
    using Microsoft.SharePoint.ApplicationPages;
    
    public partial class retrieve_password : System.Web.UI.Page
    {
       protected void SendPassword_Click(object sender, EventArgs e)
        {
           if (Page.IsValid)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWeb web = SPContext.Current.Site.OpenWeb();
                    // TODO: Move email message to settings page
                    // email subject
                    string subject = "Requested Information for " + web.Title;
                    try
                    {
                        const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;
                        const long ADS_OPTION_PASSWORD_METHOD = 7;
                        const int ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0;
                        const int ADS_PASSWORD_ENCODE_CLEAR = 1;
                        AuthenticationTypes AuthTypes;  // Authentication flags.
                       int intPort;                    // Port for instance.
                        DirectoryEntry objUser;         // User object.
                        string strPath;                 // Server path.
                        string strPort;                 // Port for instance.
                        string strServer;               // DNS name of the computer with
                        //   the AD LDS installation.
                        string strUser;                 // User DN.
                        string strUserName;
                        strUserName = "testuser";
                        // Construct the binding string.
                        strServer = "localhost";
                        strPort = "389";
                        string strAdamSource = System.Configuration.ConfigurationManager.AppSettings["AdamSource"];
                        strUser = "CN=" + strUserName.ToString().Trim() + strAdamSource.ToString(); // 
                        strPath = String.Concat("LDAP://", strServer, ":", strPort, "/", strUser);
                        AuthTypes = AuthenticationTypes.ServerBind;
                        // Bind to user object using LDAP port.
                        try
                        {
                            objUser = new DirectoryEntry(strPath, strUserName.ToString().Trim(), "ashish@123", AuthTypes);
                            objUser.RefreshCache();
                        }
    
                        catch (Exception ex)
                        {
    
                            if (ex.Message.Contains("unknown user name or bad password"))
                            {
    
                               //output.Text = "<br>" +  "<b><font color='#FF0000'>Please enter your correct current password.</font></b>" + "<br><br>"; 
                                Response.Write("<br>" + "<b><font color='#FF0000'>Please enter your correct current password.</font></b>" + "<br><br>");
                            }
                            else
                            {
                                //output.Text = "<br>" + "<font color='#FF0000'>" + "<b>Error:   Bind failed." + " - " + ex.Message + "</b></font>" + "<br>";
                                Response.Write("<br>" + "<font color='#FF0000'>" + "<b>Error:   Bind failed." + " - " + ex.Message + "</b></font>" + "<br>");
    
                           }
    
                            return;
                        }
    
                        //output.Text += "<br>" + "Error:   Bind Succesfull";
                        // Set port number, method, and password.
                        intPort = Int32.Parse(strPort);
    
                        try
    
                        {
                            //  Be aware that, for security, a password should
                            //  from the user interface.
                            objUser.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_PORTNUMBER, intPort });
                            objUser.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_METHOD, ADS_PASSWORD_ENCODE_CLEAR });
                            objUser.Invoke("SetPassword", new object[] { "password@123" });
                            //objUser.Invoke("ChangePassword",  new object[] {oldpassword.Text.ToString(), newpassword.Text.ToString()} );
                            objUser.CommitChanges();
                            SPUtility.SendEmail(web, false, false, "user@domain.com", "Password is changed for " + strUserName.ToString(), strUserName.ToString() + " has changed the password. New Password is ");
                        }
    
                       catch (Exception ex1)
                        {
    
                           Response.Write(ex1.Message + "<br>");
                            return;
                        }
    
                        //output.Text = "<br>" +  "<b><font color='#0000FF'>Password is changed successfully.</b></font>" + "<br><br>";
                        return;
                    }
    
                    catch (Exception error)
    
                    {
                        //output.Text = "<br>" + "<b><font color='#FF0000'>User Password Change Error:\n" + error.StackTrace.ToString() + "\n" + error.Message.ToString()+ "</font>"+ "<br>";
                    }
                    // construct message body
                    string body = "You have requested your password from " + web.Title + ".\n\r";
    
                    body += "Your password is: " + "test" + ".\n\r";
                    body += "Thank you";
                    // send email
                    SPUtility.SendEmail(web, false, false, "user@domain.com", subject, body);
    
                    web.Dispose();
                });
            }
        }
    
    }
    
    

     

     2. Added followinline in web.config

    <SafeControl Assembly="mypwd, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0d3777c01f5dde2b" Namespace="mypwd.retrieve_password" TypeName="*" Safe="True" />


     

     

     

    • Edited by Avian123 Tuesday, May 26, 2009 5:57 PM
    Tuesday, May 26, 2009 5:47 PM
  • it happens  .. sometimes it takes time to find one small thing .. happens most of the time with me ..

    okay coming back to your prob


    Open your web.config 

    Under  Authorization tag add  following  and see if that works ?

    <authorization>
    
    <allow users="*" />
    
    </authorization>
    

     

     


    http://mykbdump.blogspot.com/
    Tuesday, May 26, 2009 5:52 PM
  • it is already set in web.config.

    As I already mentioedn earlier that I am using FBA login. If I logged in, thne I am able to reset the password, but If I am not logged in in that case it wont allow you change the pasword and redirect back to login.aspx. Becuase here username/password cookies are not creating, but if you logged thne cookies will ceate automatically.

    Somehow we have to handle annonymous access in this scenerion.

    Please advise

    Tuesday, May 26, 2009 6:15 PM
  • Can you try    inheriting your code behind from


    UnsecuredLayoutsPageBase


    rather than System.Web.UI.Page 

    like

    public partial class retrieve_password : UnsecuredLayoutsPageBase

    build and update the assembly in gac iisreset and check now if it works?

    http://mykbdump.blogspot.com/
    • Edited by AGupta24 Tuesday, May 26, 2009 6:40 PM syntax addition
    Tuesday, May 26, 2009 6:38 PM
  • You can update AD only with required credentials. The useraccount using which you are trying to change password should have administrator or password change credential on AD. I think you should check the credential of the user on Active Directory.

    Sanjay

    Tuesday, May 26, 2009 6:44 PM
  • Yes you need to allow anonymous access for your page, but I don't think that will be a good idea as it will lead to security issues.  You need to only allow authenticated user to changes their password, as you need to know who is changing the password and with annonymous access you don't get user's identity.

    Thanks,
    Suhaib Khan 
    Tuesday, May 26, 2009 6:44 PM
  • Hello

    AGupta24 - Hello I already tried this, everytime it is redirecting to http://portal/_layouts/login.aspx?ReturnUrl=%2f_layouts%2fAccessDenied.aspx

    Sanjay Patel - As this portal for ADAM user and they are already part of Administrator group, because they are able to change the password once they are loggied in

    Suhaib - I am creating password for those users, who forget their password, so by entering their username they will get an email with new password. I know  my code is not completed, but before finalise code I like to the page should be workable. Can you give an idea how can I allow annonmouys access to my page?

    Please advise gentlemans

    Tuesday, May 26, 2009 6:50 PM
  • okay can you try couple of things  : 

    1.  removing the inherit tag in your page aspx  and see if still you  facing the error

    2.   Copy all the files  in _layouts  folder     (copy it dont cut it)

    3. create a new folder in layouts    and paste all the files in that  folder  and update your login page tag accordingly  in web.config


    now try accessing the page
    http://mykbdump.blogspot.com/
    Tuesday, May 26, 2009 7:07 PM
  • Assuming that your page is under _layouts folder, open IIS server, expand "Web Sites", expand your site, expand _layouts, once you get to your file, go to file properties, click on file security tab, click on Edit and enable annonmouys access for your page, also make sure that you uncheck "Integrated Windows Authentication".

    Thanks,
    Suhaib Khan

    Tuesday, May 26, 2009 7:11 PM
  • If I remove inherit tag, thne I how it wil work, it will look for click event, please explain .

    Secondly I removed

    <%

    @ Page language="C#" MasterPageFile="~/_layouts/simple.master" Inherits="retrieve_password ,mypwd, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0d3777c01f5dde2b" %>

    and re-added original one

    <%

    @ Page Language="C#" MasterPageFile="~/_layouts/simple.master" CodeFile="PasswordReset.aspx.cs" Inherits="retrieve_password" AutoEventWireup="true" %>

     


    I created new folder under layout, copy aspx and cs file here. I modified the login page as well as web.config, aprt from this I also added following in web.config, but No Luck, same behaviour.

    <location path="_layouts/mypassword/passwordreset.aspx">
    <system.web>
    <authorization>
    <allow users="*"/>
    </authorization>
    </system.web>
    </location>


    Tuesday, May 26, 2009 7:37 PM
  • I checked in IIS and related page, "Enable Annonmouys Access" is already checked and "Integrated Windows Authentication" is already unchecked.

    Tuesday, May 26, 2009 7:39 PM
  • Hello

    I did followings, it works. I know it is not permanent solution. I have added following in global.asax (http://blogs.devhorizon.com/reza/?p=508)

    <script RunAt='server'>
        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Context.Request.Cookies[cookieName];
            if (authCookie == null)
            {
                FormsAuthentication.SetAuthCookie("sachinp", false);
            }      
        }
    </script>

    It works perfect, but when I click on cancel button it automatically redirect to main portal page rather than login.aspx, becuase cookies is created.

    Is there any way to stop this on logged on oportal and redirect to login page.


    Tuesday, May 26, 2009 8:23 PM