I keep getting the error The server could not be contacted. When i'm trying to run my code:
I've searched for a few hours, and i'm still unable contact the server.
DirectorySearcher directorySearcher = new DirectorySearcher();
string path = directorySearcher.SearchRoot.Path;
DirectoryEntry directoryEntry = new DirectoryEntry(path);
PrincipalContext pricipalContext = new PrincipalContext(ContextType.Domain, "LDAP://domain.dk/DC=domain,DC=dk");
//GroupPrincipal group = GroupPrincipal.FindByIdentity(pricipalContext, "(CN=" + department + ")");
GroupPrincipal group = GroupPrincipal.FindByIdentity(pricipalContext, "(CN=" + department + ")");
if (group != null)
{
foreach (Principal principal in group.Members)
{
UserPrincipal tu = principal as UserPrincipal;
DirectoryEntry de = tu.GetUnderlyingObject() as DirectoryEntry;
var store = de.InvokeGet("physicalDeliveryOfficeName").ToString();
var storeNumber = de.InvokeGet("description").ToString();
employees.Add(new AdEmployees() { name = principal.Name, phone = tu.VoiceTelephoneNumber, email = tu.EmailAddress, store = store.ToString(), storeNumber = storeNumber.ToString(), link = GenerateLink(principal.Name) });
}
}
Note: I changed my domain where the AD is located to domain.
The key statement here seems to be "I changed my domain where the AD is located to domain."
Ensure the application server is pointed to the correct DNS server.
Ensure the client is pointed to the correct DNS server.
This connection string looks wrong: PrincipalContext pricipalContext = new PrincipalContext(ContextType.Domain, "LDAP://domain.dk/DC=domain,DC=dk");
Connection string in #3 might work better like this:
PrincipalContext pricipalContext = new PrincipalContext(ContextType.Domain, "DOMAIN", "DC=domain,DC=dk");
Related
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'm trying to get all the user's groups in the active directory with c# code.
This is my code:
private List<GroupPrincipal> GetGroups()
{
string userName = User.Identity.Name;
string host = Request.Url.Host.ToLower();
List<GroupPrincipal> result = new List<GroupPrincipal>();
UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, host), IdentityType.SamAccountName, userName);
foreach (GroupPrincipal group in user.GetGroups())
{
result.Add(group);
}
return result;
}
I receive an error on the row that starts with UserPrincipal user that says that the server could not be connected. I'm running my code from the server itself so I can connect it.
What am i doing wrong?
Thank you in advance!
To connect with Active Directory, Create PrincipalContext object.
PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "MyDomain",
"DC=MyDomain,DC=com");
Code to get all Groups:
Create GroupPrincipal object and call SearchGroups() which returns list of all groups of given domain.
private void ListGroups(){
GroupPrincipal insGroupPrincipal = new GroupPrincipal(insPrincipalContext);
insGroupPrincipal.Name = "*";
SearchGroups(insGroupPrincipal);}
private void SearchGroups(GroupPrincipal parGroupPrincipal)
{
List<Principal> oList = new List<Principal>();
PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
insPrincipalSearcher.QueryFilter = parGroupPrincipal;
PrincipalSearchResult<Principal> results = insPrincipalSearcher.FindAll();
foreach (Principal p in results)
{
oList.Add(p);
}
}
This link will also help you -
http://www.codeproject.com/Articles/38344/Using-System-DirectoryServices-AccountManagement
My code is to check the logged user and retrieve his data as Image, Name, Department as this application work on network. I tested my code and it worked well at Localhost but when I deployed on the company server it doesn't work.
The authentication is windows .
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchScope = SearchScope.Subtree;
string UserName = Page.User.Identity.Name;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", UserName.Split('\\')[1]);
SearchResult findUser = searcher.FindOne();
if (findUser != null)
{
DirectoryEntry user = findUser.GetDirectoryEntry();
LoggedUser = user.Properties["displayName"].Value.ToString();
LoggedEmail = user.Properties["mail"].Value.ToString();
}
I'm using DirectorySearcher to search for a user entry in LDAP server.
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://myserver/OU=People,O=mycompany";
de.AuthenticationType = AuthenticationTypes.None;
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(uid=" + model.UserName + ")";
SearchResult result = deSearch.FindOne();
I'm able to get th intended output in result variable.
However If I try to authenticate the same user by providing password in directory entry, I always get following error.
"The user name or password is incorrect."
DirectoryEntry entry = new DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);
DirectorySearcher search = new DirectorySearcher(
entry,
"(uid=" + username + ")",
new string[] { "uid" }
);
search.SearchScope = System.DirectoryServices.SearchScope.Subtree;
SearchResult found = search.FindOne(); ->>>>>this is where I get wrong credential error.
The username and password are for the user I want to authenticate.
Can anyone tell me what I'm doing wrong here or how to debug this.
This username, password within this line:
DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);
should be for an account that has permission for directory lookup. It could be a service account or testing purpose try with your own. This shouldn't be the user/pass of someone who you are trying to authenticate.
If you want to authenticate, you can use following steps using PrincipalContext:
using(var context = new PrincipalContext(ContextType.Domain, "mydomain", "mydomain\serviceAcct", "serviceAcctPass")) {
//Username and password for authentication.
return context.ValidateCredentials(username, password);
}
"serviceAcct" = an account within domain users that has permission for directory lookup.
"serviceAcctPass" = password for that service account.
As I said, for testing you can try with your own user/pass context.
Also, make sure supplied username has either "domain\username" or "username#domain" formatting.
Here we are getting the active directory user details and we can use DomainName and UserRole from web.config file
bool isAdmin = false;
RegisterInput model = new RegisterInput();
NewUserInput usr = new NewUserInput();
SearchResultCollection results;
string mobileNumber = string.Empty;
using (DirectoryEntry domainEntry = new DirectoryEntry("LDAP://" + AppSettings.DomainName))
{
using (DirectorySearcher searcher = new DirectorySearcher(domainEntry, "userPrincipalName=" + userName + "#" + AppSettings.DomainName) { Filter = string.Format("(&(objectClass=user)(samaccountname={0}))", userName) })
{
results = searcher.FindAll();
if (results.Count > 0)
{
usr.FirstName = results[0].GetDirectoryEntry().Properties["givenName"].Value.ToString();
usr.LastName = results[0].GetDirectoryEntry().Properties["sn"].Value?.ToString();
usr.EmailAddress = results[0].GetDirectoryEntry().Properties["mail"].Value?.ToString();
mobileNumber = results[0].GetDirectoryEntry().Properties["mobile"]?.Value?.ToString();
dynamic userRoleList = results[0].GetDirectoryEntry().Properties["memberOf"];
if (userRoleList != null)
{
foreach (var role in userRoleList)
{
string[] split = role.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
bool result = split.Any(x => x.ToLowerInvariant() == AppSettings.UserRole.ToLowerInvariant());
if (result)
{
isAdmin = true;
break;
}
}
}
}
}
}
model.NewUser = usr;
I'm trying to add a local user account on a non-domain joined machine. I have tried just about everything I can think of. I have this working on machines in the same domain, but not on off-domain machines. I can ping and TS to this server, but can't seem to add an admin.
Is it possible to use DirectoryEntry to do this?
Here's the code I currently have (slightly altered for readability):
private string AddLocalAdmin_NonDomain(string ComputerName)
{
StartImpersonation(); //Uses advapi32.dll->LogonUser()
string ErrMsg = "";
const int ADS_UF_DONT_EXPIRE_PASSWD = 0x10000;
DirectoryEntry AD = new DirectoryEntry("WinNT://" + ComputerName + ",computer", ComputerName + "\\" + UserCredentials.Username, UserCredentials.Password);
object n = AD.NativeObject;
DirectoryEntry NewUser = AD.Children.Add(Username, "user");
NewUser.Invoke("SetPassword", new object[] { Password });
if (!PasswordExpires)
{
int val = ADS_UF_DONT_EXPIRE_PASSWD;
NewUser.InvokeSet("userFlags", new object[] { val });
}
NewUser.CommitChanges();
DirectoryEntry grp;
grp = AD.Children.Find("Administrators", "group");
if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); }
EndImpersonation(); //Ends the impersonation
return ErrMsg; //returns "Access Denied"
}
You can use
System.DirectoryServices.AccountManagement
and to achive that here is the code
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine);
//Create New User
UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, "Your UserName", "Your Password", true /*Enabled or not*/);
oUserPrincipal.UserPrincipalName = "Your UserName";
oUserPrincipal.GivenName = "Given Name";
oUserPrincipal.Surname = "Surname";
oUserPrincipal.Save();
//Add User to Group
GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, "Your Group Name");
oGroupPrincipal.Members.Add(oUserPrincipal);
oGroupPrincipal.Save();
for a full implementation go here http://anyrest.wordpress.com/2010/06/28/active-directory-c/