I am trying to add a none UserPrincipal field to a small application, but I just cannot get it to work. I tried several ways to do this simple task, but I cannot get anything to work for me. I am trying to ADD a field called Company to be inserted into the Active Directory, but Company is not a field that can be inserted...
Any ideas? Please post a code example if you have one. I have this so far:
public bool CreateNewUser(string sUserName, string sPassword, string sGivenName, string sSurname, string email, string phone)
{
if (!IsUserExisting(sUserName))
{
string sOU = "OU=Users,OU=External,DC=external,DC=rootteck,DC=com";
PrincipalContext oPrincipalContext = GetPrincipalContext(sOU);
UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, sUserName, sPassword, true /*Enabled or not*/);
//User Log on Name
oUserPrincipal.Name = sUserName;
oUserPrincipal.UserPrincipalName = sUserName + "#external.rootteck.com";
oUserPrincipal.GivenName = sGivenName;
oUserPrincipal.Surname = sSurname;
oUserPrincipal.EmailAddress = email;
oUserPrincipal.DisplayName = sGivenName + " " + sSurname;
if (phone != string.Empty) { oUserPrincipal.VoiceTelephoneNumber = phone; }
oUserPrincipal.PasswordNeverExpires = true;
oUserPrincipal.Save();
return true;
}
else
{
return false;
//return GetUser(sUserName);
}
}
Related
how to retrieve gMSA account password in C#?
I need to use gMSA account to disable/enable AD account.
But I don't know how to get gMSA password?
public static bool DisableUserAccount(string sUserName)
{
UserPrincipal oUserPrincipal = GetUserForDoamin("D-Domain", sUserName);
oUserPrincipal.Enabled = false;
oUserPrincipal.Save();
return true;
}
public static UserPrincipal GetUserForDoamin(string sDomain, string sUserName)
{
PrincipalContext PrincipalDomain = null;
PrincipalDomain = GetPrincipalContext("D-Domain", "NONE"); ;
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(PrincipalDomain, sUserName);
return oUserPrincipal;
}
public static PrincipalContext GetPrincipalContext(string sDomainZone, string sOU)
{
PrincipalContext ServerCredentials = null;
string sDomainName = "";
sDomainName = "D-Domain";
ServerCredentials = new PrincipalContext(ContextType.Domain, sDomainName, "gMSA$", gMSApassword);
break;
return ServerCredentials;
}
At [GetPrincipalContext], gMSApassword is not nullable column. I try "" & null, but it is not working.
I don't know how to setup.
I am new to LDAP related coding and today I am asked to develop a code to check the users authentication against LDAP.
The tutorials I have found online are so simple but our company's Directory is so complicated that I don't know how to write a code for that. Here is the info of the LDAP . I have changed the company name to hide the name.
uri = ldaps://ABC.ad.XYZ.com:636
user_filter = memberOf=CN=TENXAIRFLOWPROD,OU=Security Groups,OU=Normal Users and Groups,OU=Account Management Services,OU=AD Master OU,DC=ABC,DC=ad,DC=XYZ,DC=com
user_name_attr = sAMAccountName
superuser_filter = memberOf=CN=TENXAIRFLOWPROD_ADM,OU=Security Groups,OU=Normal Users and Groups,OU=Account Management Services,OU=AD Master OU,DC=ABC,DC=ad,DC=XYZ,DC=com
bind_user = SCGLOBAL\twiki
bind_password_cmd = python /bns/tenx/airflow/ldap_password.py
basedn = DC=ABC,DC=ad,DC=XYZ,DC=com
search_scope = SUBTREE
Here is a code I have developed but it gives me error:
string username = "myUserName";
string domain = "ldaps://ABC.ad.XYZ.com:636";
string pwd = "myPasword";
try
{
DirectoryEntry entry = new DirectoryEntry(domain, username, pwd);
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
lblError.Text=("Login Successful");
//search some info of this user if any
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
SearchResult result = search.FindOne();
}
catch (Exception ex)
{
lblError.Text=("Login failed: " + ex.ToString());
}
Could anybody help plz?
Comment: According to the admin , I have been assigned to the group in AD. But how can I make sure I can access it?
It seems like Active Directory. If so, you could just use PrincipalContext.
public bool ValidateCredentials(string domain, string username, string password)
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
return context.ValidateCredentials(username, password);
}
}
public bool IsUserInAdGroup(string domain, string username, string adGroupName)
{
bool result = false;
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
var user = UserPrincipal.FindByIdentity(context, username);
if (user != null)
{
var group = GroupPrincipal.FindByIdentity(context, adGroupName);
if (group != null && user.IsMemberOf(group))
result = true;
}
}
return result;
}
Please make sure to reference System.DirectoryServices.AccountManagement.
I am facing a strange issue.
I want to know whether user's AD account is disabled or not by providing user's email as the parameter.
Below code is working great for me for some set of users in our Org.
But for some other set of users its returning null- though I can able to verify these set of users in AD manually.
Can you please help me to over come from this issue.
private string GetCurrentDomainPath()
{
DirectoryEntry de =
new DirectoryEntry("LDAP://RootDSE");
return "LDAP://" +
de.Properties["defaultNamingContext"][0].
ToString();
}
public bool? FindAccountStatusByEmail(string email)
{
using (DirectorySearcher dSearch = new DirectorySearcher(new DirectoryEntry(GetCurrentDomainPath())))
{
dSearch.SearchScope = SearchScope.Subtree;
dSearch.Filter = "(&(objectCategory=person)(sAMAccountName=*)(mail=" + email.Trim() + "))";
SearchResult sResult = dSearch.FindOne();
if (sResult != null)
{
DirectoryEntry de = sResult.GetDirectoryEntry();
return IsActive(de);
}
else
{
return null;
}
}
}
private bool IsActive(DirectoryEntry de)
{
if (de.NativeGuid == null)
{
return false;
}
int flags = (int)de.Properties["userAccountControl"].Value;
return !Convert.ToBoolean(flags & 0x0002);
}
Update-1: Lets say I have one user's email address : abac#mydomain.com
When I passing this email address through the code, its returning null.
But when I am searching it in through windows provided tool(Find Users,Contacts and Groups) I am able to retrieve the user.
But just now noticed that in "E-mail :" section that user's email is different
say abac#mydomainlbs.com in the above picture.
I have this code where I can change the display name, password, etc. in the Active Directory
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName);
userPrincipal.DisplayName = "Some NAME";
userPrincipal.SetPassword("NEW_PASSWORD");
userPrincipal.Save();
I have looked at the properties of userPrincipal and I can not find the phone number property. My question is how do I change the phone number for the User in the code.
Thank You
Correction (Sorry for all the edits):
Here's what I do......
public static void SetUserInfo(string userName)
{
var dsDirectoryEntry = new DirectoryEntry("LDAP://xxxx/DC=xx,DC=xxx", "ADusername", "ADpassword");
var dsSearch = new DirectorySearcher(dsDirectoryEntry) { Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))" };
var dsResults = dsSearch.FindOne();
var myEntry = dsResults.GetDirectoryEntry();
//myEntry.Properties[property].Value = value;
myEntry.Properties["telephoneNumber"].Value = "222-222-2222";
myEntry.CommitChanges();
}
the following code was working for 3 months without any problems.
Since today I am getting the following error;
“Exception has been thrown by the target of an invocation”
and the inner exception;
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)"
The authentication function works. Here are my functions;
public bool Authenticate(string strUserName, string strPassword)
{
bool authenticated = false;
using (
var entry = new DirectoryEntry("LDAP://myldapserver", strUserName + "#domain", strPassword,
AuthenticationTypes.Secure))
{
try
{
object nativeObject = entry.NativeObject;
authenticated = true;
}
catch (DirectoryServicesCOMException ex)
{
return false;
}
}
return authenticated;
}
And the ChangePassword Method;
public bool ChangePassword(string strUserName, string strOldPassword, string strNewPassword)
{
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;
string strPort = "636";
int intPort;
intPort = Int32.Parse(strPort);
try
{
string strUserString = "domain" + #"\" + strUserName.Trim();
var entry = new DirectoryEntry("LDAP://myldapserver", strUserString, strOldPassword,
AuthenticationTypes.Secure);
var search = new DirectorySearcher(entry);
string strFilter = "(SAMAccountName=" + strUserName + ")";
search.Filter = strFilter;
SearchResult result = search.FindOne();
DirectoryEntry user = result.GetDirectoryEntry();
user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_PORTNUMBER, intPort });
user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_METHOD, ADS_PASSWORD_ENCODE_CLEAR });
**user.Invoke("SetPassword", new object[] { strNewPassword });**
user.CommitChanges();
user.Close();
}
catch (Exception exception)
{
string msg = exception.InnerException.Message;
return false;
}
return true;
}
It throws the expcetion when I invoke the SetPassword property.
Any help would be greatly appreciated.
Here is the example:-
PrincipalContext pr = new PrincipalContext(ContextType.Domain, "corp.local", "OU=" + OU + ",OU=Users,dc=corp,dc=local", username, password);
UserPrincipal us = new UserPrincipal(pr);
To Change the Password
user.SetPassword("setPassword");
If you want the user should change the password at next Logon, you can use like this.
user.ExpirePasswordNow();
Here is your full code:-
public static Boolean ResetPassword(string username, string password, string DomainId, string setpassword, Boolean UnlockAccount,Boolean NextLogon)
{
PrincipalContext pr = new PrincipalContext(ContextType.Domain, "corp.local", "dc=corp,dc=local", username, password);
UserPrincipal user = UserPrincipal.FindByIdentity(pr, DomainId);
Boolean flag = false;
if (user != null && user.Enabled == true)
{
if (UnlockAccount)
{
user.UnlockAccount();
}
user.SetPassword(setpassword);
if (NextLogon)
{
user.ExpirePasswordNow();
}
user.Save();
flag = true;
}
else
{
flag = false;
}
user.Dispose();
pr.Dispose();
return flag;
}
I found a good article here, if you want to use it in your way, have a look here,
http://www.primaryobjects.com/cms/article66.aspx