how to enable a user to access vpn in active directory using c# programming language.
string username = "Abc user";
string _path;
string _filterAttribute;
try
{
DirectoryEntry myLdapconnection=new DirectoryEntry("domain");
myLdapconnection.Path = "LDAP://OU=,OU=,DC=,DC=,DC=";
myLdapconnection.AuthenticationType = AuthenticationTypes.Secure;
object obj = myLdapconnection.NativeObject;
DirectorySearcher search = new DirectorySearcher(myLdapconnection);
search.Filter = "(cn=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
s="True";
if (null == result)
{
s= "false";
}
// Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
s="Error authenticating user. " + ex.Message;
}
from the above code what the function of following statement is?
object obj = myLdapconnection.NativeObject;
Is this the statement to enable vpn?
if I add user to group then will he can use vpn connection?
Since obj is not used in the above code; it has no function and has nothing to do with VPN.
The code seems like it is trying to verify that a user exists, BUT it is weird.
Related
I am tasked with implementing single sign-on for our customers as part of our next release, the idea is as follows:
When our customer has access to the website, they won't need to go through an extra login step, because they are already logged into their PC with their AD account and only accounts in AD will have can access the website.
I have tried to research and learn but there seems to be no specific guide.
I'm using web forms and AD in windows server 2019.
Please suggest steps or references to me. Thanks a lot.
using System.DirectoryServices;
using System.Collections.Generic;
namespace LdapAuthentication
{
public class LdapAuthentication
{
private string _path;
private string _filterAttribute;
public LdapAuthentication(string path)
{
_path = path;
}
public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
}
public string GetGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
try
{
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
string dn;
int equalsIndex, commaIndex;
for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
{
dn = (string)result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
}
catch (Exception ex)
{
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}
}
}
I tried to create reset password and user creation functions for Active Directory. On my PC with below code is works just fine without any error. But when I publish to the server, I received error: Exception has been thrown by the target of an invocation.
ADResult hasil = new ADResult();
DirectoryEntry de = new DirectoryEntry(_path, _adminID, _adminPassword, AuthenticationTypes.Secure);
DirectorySearcher ds = new DirectorySearcher(de);
string query = string.Format("(&(objectCategory=person)(sAMAccountName={0}))", user.userID);
ds.Filter = query;
ds.Sort.PropertyName = "CN";
ds.SearchScope = SearchScope.Subtree;
ds.CacheResults = false;
try
{
SearchResult sr = ds.FindOne();
if (sr == null)
{
hasil.errorCode = -1;
hasil.result = "User name not found in this domain.";
}
else
{
DirectoryEntry userCredentials = sr.GetDirectoryEntry();
userCredentials.Invoke("SetPassword", new Object[] { user.password });
userCredentials.CommitChanges();
userCredentials.Close();
hasil.errorCode = 0;
hasil.result = "Password for " + user.userID + " changed successfully.";
}
}
catch (Exception e)
{
hasil.errorCode = -1;
hasil.result = e.Message + "<br/>" + e.StackTrace + "<br/>" + e.Source;
}
return hasil;
Is there something configuration/settings that I missed on the server side?
I changed my code using
UserPrincipal
instead of
DirectoryEntry
and it works perfectly.
I use this code:
PrincipalContext PrincipalContext4 = new PrincipalContext(ContextType.Domain, "full_domain_name.com", "OU=User_OU,DC=domain_name,DC=co,DC=id", _adminID, _adminPassword);
UserPrincipal UserPrincipal1 = new UserPrincipal(PrincipalContext4, user.userID, user.password, true);
//User Logon Name
UserPrincipal1.UserPrincipalName = user.userID;
UserPrincipal1.Name = user.firstName + " " + user.lastName;
UserPrincipal1.GivenName = user.firstName;
UserPrincipal1.Surname = user.lastName;
UserPrincipal1.DisplayName = user.firstName + " " + user.lastName;
UserPrincipal1.Enabled = true;
UserPrincipal1.Save();
I still don't know why I use DirectoryEntry is not working on windows server 2019
That't not the exact error message,real error must be wrapped.You can write loggers or event logging after lines which you think could be culprit.You can check event log on that server if you can find elaborated stack Trace. You can check that user have admin privilege for that server to lookup in AD.
I'm trying to resolve this problem but I cannot get this to work.
The Question
What is wrong with my query?
The Code
private static void ExecuteQuery()
{
string sDomain = "10.12.14.165:389";
string sDefaultOU = "CN=GeneralUsers,CN=Company,DC=Server,DC=LDS,DC=LOCAL";
string sServiceUser = "myUser";
string sServicePassword = "myPassword";
DirectoryEntry ldapEntry = new DirectoryEntry("LDAP://" + sDomain + #"/" + sDefaultOU,
sServiceUser,
sServicePassword);
DirectorySearcher ldapSearcher = new DirectorySearcher(ldapEntry);
//Error Occurs here
SearchResultCollection ldapResult = ldapSearcher.FindAll();
}
The Error
# SearchResultCollection ldapResult = ldapSearcher.FindAll();
Exception: There is no such object on the server.
Attention
The Object DOES Exist
The problem occured in the LDS Configuration. the user I was authenticating with had no rights to the LDS, the query I was using was working fine.
I'm passing username and password to check whether a user is valid from Active Directory.
Here is my code :
private bool ValidUser(string name, string userPwd)
{
string UserName = "XXXXXXXXXX";
string Password = "XXXXXXXXXXXXX";
DirectoryEntry objRootEntry = new DirectoryEntry("XXXXXXXX.com", UserName, Password);
DirectorySearcher objADSearcher = new DirectorySearcher(objRootEntry);
objADSearcher.Filter = ("(&(sAMAccountType=xxxxxxxxx)(samAccountName=" + name + "))");
SearchResult objResult = objADSearcher.FindOne();
DirectoryEntry objLoginEntry = (objResult != null) ? objResult.GetDirectoryEntry() : null;
if (objLoginEntry != null)
{
return true;
}
return false;
}
Now it checks the user name alone.I need to check whether the entering password (userPwd) matches with the Active directory. How to do that.
Please help me out.
//You are entering password while finding in Directory entry is enough. Don't need to check again
Check this detail code
public bool ValidateUser(string domain, string username, string password,string LdapPath, out string Errmsg)
{
Errmsg = "";
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(LdapPath, domainAndUsername, password);
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
// Update the new path to the user in the directory
LdapPath = result.Path;
string _filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
Errmsg = ex.Message;
throw new Exception("Error authenticating user." + ex.Message);
}
}
How to remove windows group account using C#
I'm using this code to remove user account, but I need to remove the whole group.
DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString());
DirectoryEntries users = localDirectory.Children;
DirectoryEntry user = users.Find(userDn);
users.Remove(user);
I need to remove the Group with it's users.
public void Delete(string ouPath, string groupPath)
{
if (DirectoryEntry.Exists("LDAP://" + groupPath))
{
try
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + ouPath);
DirectoryEntry group = new DirectoryEntry("LDAP://" + groupPath);
entry.Children.Remove(group);
group.CommitChanges();
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
}
else
{
Console.WriteLine(path + " doesn't exist");
}
}
Howto: (Almost) Everything In Active Directory via C#