Solved

change password from asp.net

Posted on 2004-09-04
20
24,750 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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
 

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

726 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