Solved

change password from asp.net

Posted on 2004-09-04
20
24,728 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
ID: 11982860
orthe id under which it's running hasn't rights
0
 

Author Comment

by:vcorn
ID: 11982908
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
ID: 11983098
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
ID: 11983122
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
ID: 11983383
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
ID: 11983393
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
ID: 11983396
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
ID: 11983451
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
ID: 11983551

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
ID: 11983570
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:vcorn
ID: 11983571
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
ID: 11983590

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

Author Comment

by:vcorn
ID: 11984553
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
ID: 11985033

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
ID: 11986789
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
ID: 11987774
>> 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
ID: 11990823
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
ID: 11995148
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
ID: 12470665
---
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
ID: 13498251
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Image(7) 1 53
Please explain "Multi-Tenant Services" 5 63
Code works but I need to redo it and assign values to Model 7 32
Error on link 14 37
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

910 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

22 Experts available now in Live!

Get 1:1 Help Now