Solved

change password from asp.net

Posted on 2004-09-04
20
24,723 Views
Last Modified: 2011-08-18
hi,
i want to change active directory user password from asp.net, but it always gives me access denied, does this mean asp.net can't change password?
Plz help
0
Comment
Question by:vcorn
  • 9
  • 5
  • 4
  • +2
20 Comments
 
LVL 22

Expert Comment

by:cookre
Comment Utility
orthe id under which it's running hasn't rights
0
 

Author Comment

by:vcorn
Comment Utility
i'm able to access the directory, but unable to set password for the user
using ADSI IADsUser.SetPassword(newPass);
0
 
LVL 22

Expert Comment

by:cookre
Comment Utility
from:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adsi/adsi/iadsuser_setpassword.asp

"In Active Directory, the caller must have the Reset Password extended control access right to set the password with this method."

0
 

Author Comment

by:vcorn
Comment Utility
yeah..the problem is that i have run my code using C# console app and it works,
it just doesn't work when i go to asp.net, how to handle this?
0
 
LVL 22

Expert Comment

by:cookre
Comment Utility
When you run the c# code, it's running under your rights.  The ASP code is running under diminished rights.

You can either modify the server to use elevated rights for all connections, or modify the ASP code to logon as a user with the rights to do the SetPassword().
0
 

Author Comment

by:vcorn
Comment Utility
no, indeed in C# i supply the code with username and password
for example :  new DirectoryEntry(path,username,password) to change password.
and you are right that i don't have such rights in asp to do that, but how do i give the rights?
i have set up anonymous account in IIS that run the asp with administrator account, but it doesn't solve anything, any suggestion?
0
 

Author Comment

by:vcorn
Comment Utility
i follow the steps in msdn, "form authentication with active directory" but it's still the same, i'm mad now
0
 
LVL 22

Expert Comment

by:cookre
Comment Utility
In the description of DirectoryEntry(), I note the reference to "Using Libraries From Partially Trusted Code":
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconusinglibrariesfrompartiallytrustedcode.asp?frame=true

I'm not mad, but I am lost.
0
 
LVL 20

Expert Comment

by:ihenry
Comment Utility

Do you have password policy enabled in the active directory server? And check if the supplied password is strong enough to meet the complexity settings.
0
 

Author Comment

by:vcorn
Comment Utility
i have disabled such policy previously ..all password has been accepted, so i don't think it's the problem...since i also can change the password if i put my code in  C# console app
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:vcorn
Comment Utility
i have set the impersonate = true, and hmm...why i have so many troubles in asp.net...desperateeeeeeeeee
0
 
LVL 20

Expert Comment

by:ihenry
Comment Utility

can you paste some of your code here? and also the complete error message if possible.
0
 

Author Comment

by:vcorn
Comment Utility
here it is:

DirectoryEntry root = new DirectoryEntry(domain,username,oldpass);
DirectorySearcher ds = new DirectorySearcher(root);
ds.CacheResults = true;
ds.SearchScope = SearchScope.Subtree;
ds.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))";
SearchResult res = ds.FindOne();
if(res == null)
    throw new Exception("User not found.");
DirectoryEntry user = new DirectoryEntry(res.Path,username,oldpass);
IADsUser _user = (IADsUser)user.NativeObject;
_user.SetPassword(newpass); //this is the last line that gives access denied

The following are error messages:

Access is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access is denied.

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

To grant ASP.NET write access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

Source Error (line 33):


Line 31:                   DirectoryEntry user = new DirectoryEntry(res.Path,username,oldpass);
Line 32:                   IADsUser _user = (IADsUser)user.NativeObject;
Line 33:                   _user.SetPassword(newpass);
Line 34:             }
Line 35:       }
 


0
 
LVL 20

Expert Comment

by:ihenry
Comment Utility

The article posted by cookre means the "Reset Password" extended right permits resetting password on user account without need to know the original password. This permission usually given out to Admins (or Domain Admins) or Account operators (Domain Account operators). And with your code now, it seems you need to grant such permission to each and every user in your application.

I usually prefer to use Change Password instead of SetPassword, since it needs only "Change Password" extended right which is given to regular users for their own objects.

Or you can actually use the User-Password attribute directly because the update Privilege to this attribute is given to domain administrator or account owner.

User-Change-Password extended right
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adschema/adschema/r_user_change_password.asp

IADsUser::ChangePassword
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adsi/adsi/iadsuser_changepassword.asp

User-Password attribute
http://msdn.microsoft.com/library/en-us/adschema/adschema/a_userpassword.asp
0
 

Author Comment

by:vcorn
Comment Utility
What did you mean by  "I usually prefer to use Change Password instead of SetPassword, since it needs only "Change Password" extended right which is given to regular users for their own objects."

does it make any difference? did you mean that user can change their own password if i use "change password" and they can't if i use "set password" method?

if it's true..i have try changePassword method before i use set password, but it always gives me error because the complexity of password didn't match, i have disable such policy in group policy, and i can put any password manually, but why the policy still apply when i use "change password" method.

and could you explain what you mean by "Or you can actually use the User-Password attribute directly because the update Privilege to this attribute is given to domain administrator or account owner", how do i use the User-Password attribute?

Thanks a lot
0
 
LVL 20

Accepted Solution

by:
ihenry earned 125 total points
Comment Utility
>> What did you mean by  "I usually prefer...
>> ..does it make any difference...
It should make a difference. If you don't have proper rights (Administrators) you are not allowed to change your own password using SetPassword but you should be able to do so using ChangePassword. Can you imagine other people can change your password without need to know the original password?

>> if it's true..i have try changePassword...
>> ..why the policy still apply when i use "change password"...
I'm not sure why you hit to this problem, one reason I guess is because your code didn't use any of secure binding (AuthenticationTypes property to Secure, SecureSocketsLayer or Kerberos).
--------- from MSDN
When invoke ChangePassword, ldap provider initially try to establish a secure connection. If fails, it then calls the AD specific network management API, NetUserChangePassword function.
---------
In your case it failed. And again the default ACL permits only Domain Admins and Account Operators to call NetUserChangePassword function, which is the same with SetPassword.

>> and could you explain...User-Password attribute...
You can use User-Password attribute like this,
usr.Properties["userPassword"].Value = newPassword;
usr.CommitChanges();
but it should perform the same as ChangePassword because it needs the same access rights.


NetUserChangePassword
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/netuserchangepassword.asp

0
 
LVL 20

Expert Comment

by:ihenry
Comment Utility
I use the following code to change password, you might want to give it a try.

    '
    ' This function allows the password to be changed via an Admin
    Private adminAccountName As String = "Domain\Admins"
    Private adminPassword As String = "adminpwd"
    Public Sub ChangePassword(ByVal ldapPath As String, ByVal userName As String, ByVal newPassword As String)

        Dim de As New DirectoryEntry(ldapPath, adminAccountName, adminPassword, AuthenticationTypes.Secure)
        Dim ds As New DirectorySearcher(de)
        Dim qry As String = String.Format("(&(objectCategory=person)(sAMAccountName={0}))", userName)
        ds.Filter = qry
        ds.Sort.PropertyName = "cn"

        Try
            Dim sr As SearchResult = ds.FindOne()
            Dim user As DirectoryEntry = sr.GetDirectoryEntry()
            Dim args() As Object = {"" + adminAccountName + "", "" + adminPassword + ""}
            user.Invoke("SetPassword", args)
            user.CommitChanges()
        Catch
            Throw
        Finally
            If Not IsNothing(de) Then
                de.Dispose()
            End If
            If Not IsNothing(ds) Then
                ds.Dispose()
            End If
        End Try

    End Sub

    '
    ' this function allows the password to be change via current account credentials
    Public Sub ChangePassword(ByVal ldapPath As String, ByVal userName As String, ByVal oldPassword As String, ByVal newPassword As String)

        Dim de As New DirectoryEntry(ldapPath, userName, oldPassword, AuthenticationTypes.Secure)
        Dim ds As New DirectorySearcher(de)
        Dim qry As String = String.Format("(&(objectCategory=person)(sAMAccountName={0}))", userName)
        ds.Filter = qry
        ds.Sort.PropertyName = "cn"

        Try
            Dim sr As SearchResult = ds.FindOne()
            Dim user As DirectoryEntry = sr.GetDirectoryEntry()
            Dim args() As Object = {"" + oldPassword + "", "" + newPassword + ""}
            user.Invoke("ChangePassword", args)
            user.CommitChanges()
        Catch
            Throw
        Finally
            If Not IsNothing(de) Then
                de.Dispose()
            End If
            If Not IsNothing(ds) Then
                ds.Dispose()
            End If
        End Try

    End Sub
0
 

Author Comment

by:vcorn
Comment Utility
hi ihenry,
I have found the solution, i need to set the min pass in order to remove the pass complexity policy, so now i can use change password.
Thanks for all your hints, it works now
0
 

Expert Comment

by:rextangtw
Comment Utility
---
if it's true..i have try changePassword method before i use set password, but it always gives me error because the complexity of password didn't match, i have disable such policy in group policy, and i can put any password manually, but why the policy still apply when i use "change password" method.
---

I've encountered this problem too. while using ChangePassword method, no matter how I disable the Domain's complexity policies, it just keep telling me that I am not following the complexity policy and didn't commit my Change!

I've also tried vcorn's way to set the min pass, and use AuthenticationType.Secure to link DirectoryEntry but the situation still there.

Exactly how to disable this annoying password complexity check??? although it's for good security, but now I am mad on it!

here is my code segment, I use WinNT provider on ASP.NET to change a user's password.
---
// this is the button event handler when user provided the new password credentials...
private void Button1_Click(object sender, System.EventArgs e)
{
      txtStatus.Text = "";

      string strUserName = txtUserName.Text.Trim();
      string strPassword = txtPassword.Text.Trim();
      string strNewPass = txtNewPass.Text.Trim();
      string strNewPassCfm = txtNewPassCfm.Text.Trim();

      string strADSIPath = "WinNT://" + strDomainName + "/" + strUserName + ",user";

      DirectoryEntry objDE = new DirectoryEntry(strADSIPath, strUserName, strPassword, AuthenticationTypes.Secure);

      StringBuilder mysb = new StringBuilder();

      // changing password procedures
      if (strNewPass == strNewPassCfm)
      {
            //change password by invoking ADSI changePassword method from System.DirectoryService

            try
            {
                  objDE.Invoke("ChangePassword", new object [] {strPassword, strNewPass});
                  objDE.CommitChanges();

                  mysb.Append("password changed!\n");
            }
            catch (Exception ect)
            {
                  if (ect.InnerException != null)
                  {
                        mysb.Append("error:\n" + ect.InnerException.Message + "\n");
                  }
                  else
                  {
                        mysb.Append("error:\n" + ect.Message + "\n");
                  }
            }


      }
      else
      {
            mysb.Append("typo!\n");
      }

      txtStatus.Text = mysb.ToString();

      objDE.Close();

}

---

this code works just fine in a machine that's non-AD-domain env. but I've tried this on 2 AD-Domain env. and it all tells me that I didn't follow the password complexity policies, no matter I typed new password that's match the policies or just disabled from Domain and Machine Policy Editors.

please help!

Rex
0
 

Expert Comment

by:infonetica
Comment Utility
Hi,

Im having your exact same problem.

regardless of the password it still says it doesnt meet complexity requirements.

please help if you know the answer.

Thanks in advance,

Guy
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now