How to show error messages from AD with UserPrinciple.ChangePassword()? - vb.net

I am trying to change a active directory user password through an application done by VB.net and the password is able to change when password policy is met but when I try to test it with a new password that does not satisfy the password policy, there is no error returned. Is there something I'm doing wrong?
I have already tried using DirectoryEntry instead and even though that does show an error from AD when password policy isn't met, it does not change the password when password policy is met. This is the segment of the code:
Try
Dim context As PrincipalContext = New PrincipalContext(ContextType.Domain, "corp.contoso.com", "OU=Students,DC=corp,DC=contoso,DC=com")
Dim userPrincipal As UserPrincipal = userPrincipal.FindByIdentity(context, IdentityType.SamAccountName, UserName)
Using userPrincipal
userPrincipal.ChangePassword(OldPassword, NewPassword)
userPrincipal.Save()
lreturnvalue = "Password successfully changed"
End Using
Catch ex As Exception
lreturnvalue = ex.InnerException.Message
End Try
Currently, I will be able to change the user's password if password policy requirements are met but no error is returned when it isn't met. Does anyone know why is this like that?

Related

Active Directory: Add New User C# / VB

I browsed other questions and couldn't find the answer.
What is the appropriate way to add a new user to a active directory specific group when the "current user" running the application does not have access rights to add new users?
I am currently authenticating as the domain Administrator to do it, but obviously that is a security no-no and I don't want the Administrator user's credentials hard-codeded in my code.
I assume the answers is not in my code itself but that I have to create a user in the Active Directory that has privileges to add users.
So my question is a combination of a AD and a Coding question:
1) How do I create a AD user that ONLY has access rights to add users to specific OU and CN security group?
2) Is their any way possible to not hard-code the password for this user?
Or... am I going about this entirely wrong?
Here is my current VB.NET code:
Public Function CreateUser(ByVal UserName As String, ByVal Password As String, ByVal DisplayName As String) As Boolean
Try
'Dim catalog As Catalog = New Catalog()
Dim de As DirectoryEntry = New DirectoryEntry()
de.Path = "LDAP://OU=TS2xUsers,DC=dc,DC=example,DC=com"
de.AuthenticationType = AuthenticationTypes.Secure
de.Username = "Administrator"
de.Password = "foopassword"
'1. Create user accountd
Dim users As DirectoryEntries = de.Children
Dim newuser As DirectoryEntry = users.Add("CN=" & DisplayName, "user")
newuser.Properties("givenname").Value = DisplayName
newuser.Properties("name").Value = DisplayName
newuser.Properties("displayName").Value = DisplayName
newuser.Properties("SAMAccountName").Value = UserName
newuser.Properties("userPrincipalName").Value = UserName & "#dc.example.com"
'newuser.Properties("OU").Value = "TS2xUsers"
newuser.CommitChanges()
Dim ret As Object = newuser.Invoke("SetPassword", Password)
newuser.CommitChanges()
Dim exp As Integer = CInt(newuser.Properties("userAccountControl").Value)
exp = exp And Not &H2 'enable acccount
exp = exp Or &H10000 'dont expire password
newuser.Properties("userAccountControl").Value = exp
newuser.CommitChanges()
''' 5. Add user account to groups
If MakeTSUser(newuser) = False Then
Return False
newuser.Close()
de.Close()
End If
newuser.Close()
de.Close()
Return True
Catch ex As Exception
MsgBox("Failed to create user due to the following reason: " & ex.Message, MsgBoxStyle.Critical)
Return False
End Try
End Function
Private Function MakeTSUser(ByVal deUser As DirectoryEntry) As Boolean
Try
Dim deRBGroup As New DirectoryEntry
deRBGroup.Path = "LDAP://CN=TSUsers,CN=Builtin,DC=dc,DC=example,DC=com"
deRBGroup.AuthenticationType = AuthenticationTypes.Secure
deRBGroup.Username = "Administrator"
deRBGroup.Password = "foopassword"
Dim deDomainUsers As New DirectoryEntry
deDomainUsers.Path = "LDAP://CN=Domain Users,CN=Users,DC=dc,DC=example,DC=com"
deDomainUsers.AuthenticationType = AuthenticationTypes.Secure
deDomainUsers.Username = "Administrator"
deDomainUsers.Password = "foopassword"
Dim primaryGroupToken As Object = Nothing
deRBGroup.Invoke("Add", New Object() {deUser.Path.ToString()})
deRBGroup.CommitChanges()
'Get Primary Group Token of MYGROUP
deRBGroup.Invoke("GetInfoEx", New Object() {New Object() {"primaryGroupToken"}, 0})
primaryGroupToken = deRBGroup.Properties("primaryGroupToken").Value
'Assign Primary Group Token value of MYROUP to the User's PrimaryGroupID
deUser.Properties("primaryGroupID").Value = primaryGroupToken
deUser.CommitChanges()
'Remove the User from "Domain Users" group
deDomainUsers.Invoke("Remove", New Object() {deUser.Path.ToString()})
deDomainUsers.CommitChanges()
Return True
Catch ex As Exception
Return False
End Try
End Function
What is the appropriate way to add a new user to a active directory specific group when the "current user" running the application does not have access rights to add new users?
Run the app as a user that does have those permissions... but you already know this:
I assume the answers is ... to create a user in the Active Directory that has privileges to add users.
Is their any way possible to not hard-code the password for this user?
Good question. One way to do this by setting up a Windows Scheduled Task. You can setup a task to run on demand, with no actual schedule, and to run as any user you want, including your new service account. You will have to put in the password for that user when you setup the task, but only when you first setup the task, and the actual password won't be stored... only the authentication token, which is not transferable. Then your desktop application can trigger the task to start.
Another way to do this is to grant the unprivileged HR or helpdesk users who run your app permissions to create new users just within your specific OU. In the case of a web app, you can also do this for the user account that runs the web site, as long as you have appropriate logging and auditing in place.
The other option is to create a separate service to create the users, which runs as the appropriate user. This could be a web service, where less-privileged authenticated users can post the new account information, or it could be a Windows service doing something like watching a file share, where your unprivileged users then have the ability or write to the file share. Then your program can know how to call the service or write the correct file formats into the share.

HttpContext.Current.User.Identity not populated after sign in

So I'm using AspNet Identity and I'm trying to access the User session variable in Http.Context.Current.User after signing in. I've read online that it should be automatically populated once the sign in attempt is successful. However this doesn't seem to be the case for me.
This is my code:
Dim email As String = txtEmail.Text
Dim password As String = txtPassword.Text
Dim user As ApplicationUser
If Session("LocalNetwork") Then
Await _signInManager.PasswordSignInAsync(email, password, False, False))
Dim y = HttpContext.Current.User.Identity.GetUserId
End If
The signin is successful and I'm trying to access my UsersID but it returns null.
Web config:
<authentication mode="None" />
Anyone know why?
It's because I was checking if the user was authenticated in the same request as updating them. So they wont be authenticated until the end of the request.

Request admin credentials for part of a project

I have a fairly basic VB.NET project that allows users to restore certain parts of their profiles, should it ever need to be recreated (IE Favourites, Quick Launch, that sort of thing).
I have added to the project the ability to restore these profile parts on behalf of other users, but for this you should have Administrator privileges for our Domain, and I wish the project to prompt for appropriate credentials.
Is this possible for only part of a project? I've looked in to manifests, but from my (limited) understanding it seems that they are only appropriate for for projects as a whole, as opposed to components of a project. Thanks.
If Username = "" Then
Return False
ElseIf Not Username = CurrentUsername Then
'** Require admin privilages *'
Else
Return True
End If
Answering your comment i got this:
If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
MessageBox.Show("Yes")
Else
MessageBox.Show("No")
End If
It tells if your application is being runned as admin or not.
I figured this out in the end (almost). The code below uses a Username and Password supplied in an optional 'Settings' form to check whether the current user is a member of the built-in Administrators group in our Domain.
Public Function IsAuthenticatedUser(ByVal Username As String,
Optional ByVal Group As String = "Administrators") As Boolean
Dim IsAuthenticated As Boolean = False
Try
Using RootContext2 As New PrincipalContext(ContextType.Domain,
"dynedrewett.com",
"DC=dynedrewett,DC=com",
Me.formSettings.txtUsername.Text,
Me.formSettings.txtPassword.Text & "XXX"), _
TheGroup As GroupPrincipal = GroupPrincipal.FindByIdentity(RootContext2, IdentityType.Name, Group), _
TheUser As UserPrincipal = UserPrincipal.FindByIdentity(RootContext2, IdentityType.SamAccountName, Username)
If TheGroup IsNot Nothing AndAlso TheUser IsNot Nothing Then
For Each SingleGroup As Principal In TheGroup.GetMembers(True)
If SingleGroup.Name = TheUser.DisplayName Then
IsAuthenticated = True
Exit For
End If
Next
Else
IsMember = False
End If
TheGroup.Dispose()
TheUser.Dispose()
End Using
Catch Ex As Exception
Dim ErrorForm As New formError(Ex, "Ensure that valid Administrator Credentials are specified in the application Settings.")
End Try
Return IsAuthenticated
End Function

Using DirectoryEntry.Invoke("SetPassword", ...) to set initial AD account password, I get "RPC server is unavailable" error

The company I'm working in has a web service that can create new Active Directory accounts based on information that is typed in e.g. username, firstname, lastname, OU1, OU2, etc.
This web service has been working fine on Windows Server 2003. Now I'm working on moving the web service to 2008 R2 servers. However a certain functionality doesn't work anymore, which is when it tries to set a random initial password to the newly created account.
The exception that is thrown is a TargetInvocationException containing an inner exception of COMException with a message of "The RPC Server is unavailable".
Imports System.DirectoryServices
Dim ldapPath As String = "..." 'assume valid LDAP path
Dim objContainer As DirectoryEntry = New DirectoryEntry(ldapPath, vbNullString, vbNullString, AuthenticationTypes.Secure)
objUser = objContainer.Children.Add("cn=" & Username.Trim, "user")
'sets objUser.Properties e.g. givenName, displayName, userPrincipalName, samAccountName, etc. Not important...
objUser.CommitChanges()
strPassword = RandomPassword() 'function that generates random password
objUser.Invoke("SetPassword", New Object() {strPassword})
objUser.Properties("useraccountcontrol").Value = "512" ' set as normal account
objUser.CommitChanges()
'and so on...
The error happens on the line that says:
objUser.Invoke("SetPassword", New Object() {strPassword})
Strangely the account creation itself works and I can see the new user from Active Directory Users and Computers.
I have consulted a few different people who manage the security of the DCs and the web servers, they don't really know why...
In the end I figured out a different way of setting the password, which is using the System.DirectoryServices.AccountManagement library.
So the code becomes something like this:
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Dim ldapPath As String = "..." 'assume valid LDAP path
Dim objContainer As DirectoryEntry = New DirectoryEntry(ldapPath, vbNullString, vbNullString, AuthenticationTypes.Secure)
Dim objUser As DirectoryEntry = objContainer.Children.Add("cn=" & Username.Trim, "user")
'sets objUser.Properties e.g. givenName, displayName, userPrincipalName, samAccountName, etc. Not important...
objUser.CommitChanges()
Dim domainContext As PrincipalContext = New PrincipalContext(ContextType.Domain, ...)
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, Trim(Username))
strPassword = RandomPassword() 'function that generates random password
user.SetPassword(strPassword)
user.Enabled = True 'setting these two properties
user.PasswordNotRequired = False 'result in useraccountcontrol value = 512 (normal account)
user.Save()
'and so on...
I'm mixing old code with new code in this one, but it appears to be working really well on the new servers. One thing to note is that sometimes the UserPrincipal.FindByIdentity call initially returns Nothing, I believe due to delay in the account creation or with the replication. So I have to make sure that the user object is not Nothing by trying FindByIdentity multiple times until I get the object.
Despite finding a solution (more like a way around) to the problem, still I'm confused as to why the old code does not work on the new servers, but the new one does. The error is very generic and searching the internet for clues have resulted in nothing but more confusion.
Would really appreciate if experts out there can shed some lights or even comment on the way my new code looks, any problems?
Thanks in advance.

Is it possible to authenticate an Active Directory User with an Expired password?

I have a web form that uses AD to authenticate users. I want to be able to authenticate users with expired password, and redirect them to the password change page after authentication.
if for instance, a site admin reset a users password, I use the method below, to make the user reset their password on next logon.
Public Shared Sub ForceUserToResetPassword(ByVal LDAP_URI As String, ByVal UserName As String, ByVal Auth_UserName As String, ByVal Auth_Password As String)
Dim LDAPEntry As DirectoryEntry = Nothing
Try
LDAPEntry = New DirectoryEntry(LDAP_URI, Auth_UserName, Auth_Password, AuthenticationTypes.Secure)
Dim LDAPSearch As New DirectorySearcher()
LDAPSearch.SearchRoot = LDAPEntry
LDAPSearch.Filter = "(&(objectClass=user)(sAMAccountName=" & UserName & "))"
LDAPSearch.SearchScope = SearchScope.Subtree
Dim results As SearchResult = LDAPSearch.FindOne()
If Not (results Is Nothing) Then
LDAPEntry = New DirectoryEntry(results.Path, Auth_UserName, Auth_Password, AuthenticationTypes.Secure)
End If
LDAPAccess.SetProperty(LDAPEntry, "pwdLastSet", 0)
LDAPEntry.CommitChanges()
Catch ex As Exception
End Try
End Sub
Doing this makes the user's password expire. If the user try to logon with their new password the authentication fails with "Logon failure: unknown username or bad password".
This is my auth. method:
Public Shared Function AuthADuser(ByVal LDAP_URI As String, ByVal UserName As String, ByVal password As String, ByVal Auth_UserName As String, ByVal Auth_Password As String) As Boolean
Dim IsAuth As Boolean = False
Dim LDAPEntry As DirectoryEntry = Nothing
Try
LDAPEntry = New DirectoryEntry(LDAP_URI, UserName, password, AuthenticationTypes.Secure)
Dim tmp As [Object] = LDAPEntry.NativeObject
IsAuth = True
Catch ex As Exception
LDAPEntry.Dispose()
If ex.Message.StartsWith("The server is not operational") Then
IsAuth = False
ElseIf ex.Message.StartsWith("Logon failure:") Then
Throw New ApplicationException("The Username and password combination are not valid to enter the system.")
End If
Finally
LDAPEntry.Close()
End Try
Return IsAuth
End Function
Is there a way around this?
Thanks for your help.
In my understanding, if a user is required to Change his Password at Next Logon (User's password has expired) Active-Directory will not allow us to use LDAP to determine if his password is invalid or not. This is due to the fact that a user must change password. I found here the following solution :
To determine if password is expired, you may call Win32:LogonUser(), and check the windows error code for the following 2 constants:
ERROR_PASSWORD_MUST_CHANGE = 1907
ERROR_PASSWORD_EXPIRED = 1330
I have a non official answer. As administrator you put pwdLastSet to -1 for the user where pwdLastSet is set to 0. The effect of this is to make Active-Directory believe that the password has just been changed. Then, you check the password with your AuthADuser method. Then you put back pwdLastSet to 0. I do not test it, but just imagine it, it's not so clean on the security point of view (in France we call that "bricolage").
Just tell me if it works ?
I hope it helps;
JP