I trying to implement LDAP authentication in C# Web Application.
I tried is using the below code.
try
{
using (LdapConnection conn = new LdapConnection(this.Server))
{
string uname = userName;
if (!string.IsNullOrEmpty(this.UsernamePrepend))
{
uname = string.Concat(this.UsernamePrepend, userName);
}
NetworkCredential cred = new NetworkCredential(uname, password, null);
conn.SessionOptions.SecureSocketLayer = true;
conn.SessionOptions.VerifyServerCertificate = (LdapConnection con, X509Certificate cer) => true;
conn.SessionOptions.ProtocolVersion = 3;
conn.AuthType = AuthType.Basic;
conn.Bind(cred);
}
}
catch (LdapException ldapException)
{
LdapException ex = ldapException;
if (!ex.ErrorCode.Equals(49))
{
this.LogError(ex, userName);
throw ex;
}
}
flag = true;
Every time I run it, it goes into catch block with exception LDAP server is unavailable.
Am I missing something?
Remove conn.SessionOptions.SecureSocketLayer = true; from your code
Related
I'm working on remote computer control by WMI using C#. I can connect after I have made the necessary settings on the remote computer. There is no problem so far. But when I shut down a remote computer with the Win32ShutDown command, after reboot the remote computer I received the following error:
System.Runtime.InteropServices.COMException (0x80070522): A required privilege is not held by the client. (Exception from HRESULT: 0x80070522).
How can I solve this?
My connection function:
public static ManagementScope Connect(string ip, string userName = "", string password = "")
{
ManagementScope scope = null;
try
{
ConnectionOptions opts;
scope = new ManagementScope(string.Format("\\\\{0}\\root\\cimv2", ip.Trim()));
if (!string.IsNullOrEmpty(userName))
{
opts = new ConnectionOptions
{
Username = userName,
Password = password,
EnablePrivileges = true,
Impersonation = ImpersonationLevel.Impersonate
};
scope.Options = opts;
}
scope.Connect(); //Error is thrown here
return scope;
}
catch (Exception ex)
{
scope = null;
throw ex;
}
}
My shutdown function:
static void ShutDown()
{
try
{
ConnectionOptions options = new ConnectionOptions
{
Username = "Administrator",
Password = "123",
EnablePrivileges = true,
Impersonation = ImpersonationLevel.Impersonate
};
ManagementScope scope = new ManagementScope(string.Format("\\\\{0}\\root\\cimv2", "192.168.1.50", options));
scope.Connect(); //Error is thrown here
ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem") { Scope = scope };
mcWin32.Get();
ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");
mboShutdownParams["Flags"] = 5;
ManagementBaseObject mboShutdown = null;
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
Console.ReadLine();
}
}
I am fairly new with C# and I am trying to write an SSH console application using the SSH.NET framework. So far I was able to connect to my server successfully, but now I am trying to run commands and have it display the result. Yet, my console comes out blank when I run my application. My end goal was to execute a set of commands and see the results at the end of it.
Program.cs
using Renci.SshNet;
class Program
{
//Login Parameter
const String Hostname = "somePort";
const int PortNumber = 22;
const String Username = "username";
const String Password = "root";
static void Main(string[] args)
{
//Bypass Keyboard authentication
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Username);
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
kauth.AuthenticationPrompt += new EventHandler<Renci.SshNet.Common.AuthenticationPromptEventArgs>(HandleKeyEvent);
//Grab info for connections
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, PortNumber, Username, pauth, kauth);
//Connect
using (SshClient client = new SshClient(connectionInfo))
{
try
{
//Connect to server
client.Connect();
Console.WriteLine("Connection successful");
var command = client.CreateCommand("ls");
var result = command.Execute();
command.Execute();
Console.WriteLine(result);
//Disconnect from server
client.Disconnect();
}
//Show exp message
catch (Exception exp)
{
throw exp;
}
}
}
//Handle two step auth
static void HandleKeyEvent(Object sender, Renci.SshNet.Common.AuthenticationPromptEventArgs e)
{
foreach (Renci.SshNet.Common.AuthenticationPrompt prompt in e.Prompts)
{
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
{
prompt.Response = Password;
}
}
}
}
I don't know if you have resolved this issue yet, but the solution is simple in this case.
The function:
command.Execute()
doesn't return your result.
You have to execute like you did, but then grab the result via
command.Result
It would look something like this:
var command = client.CreateCommand("ls");
command.Execute();
var result = command.Result;
Hope i could help you.
My login window uses LDAP to authenticate users. However, when validating, it always returns false.
Here is the code for validation which I got from CodeProject:
public bool fnValidateUser()
{
bool validation;
try
{
LdapConnection lcon = new LdapConnection
(new LdapDirectoryIdentifier((string)null, false, false));
NetworkCredential nc = new NetworkCredential(Environment.UserName,
txtPassword.SecurePassword, Environment.UserDomainName);
lcon.Credential = nc;
lcon.AuthType = AuthType.Negotiate;
// user has authenticated at this point,
// as the credentials were used to login to the dc.
lcon.Bind(nc);
validation = true;
}
catch (LdapException)
{
validation = false;
}
return validation;
}
txtPassword.SecurePassword is the PasswordBox. When I enter my password/pin and hit login, it displays the MessageBox for whenever validation is false.
What am I doing wrong?
UPDATE: The exception indicates "The LDAP Server is Unavailable", at this line lcon.Bind(nc);
You can try this sample piece of code.
// the username and password to authenticate
const string domain = "OU=Organization,DC=mydomain,DC=com";
string password = "mypass";
string userName = "myuser";
// define your connection
LdapConnection ldapConnection = new LdapConnection("ldap.mydomain.com:389");
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(username, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// authenticate the user
ldapConnection.Bind(networkCredential);
}
catch (LdapException ldapException)
{
//Authentication failed, exception will dictate why
}
}
I went ahead and found another approach for this, without using LDAP.
PrincipalContext adContext = new PrincipalContext(ContextType.Machine);
private async void btnLogin_Click(object sender, RoutedEventArgs e)
{
try
{
using (adContext)
{
if (adContext.ValidateCredentials(txtUsername.Text, txtPassword.Password))
{
MainWindow main = new MainWindow();
main.Show();
main.txtLoggedInUser.Text = UserPrincipal.Current.DisplayName;
this.Close();
}
else
{
MessageBox.Show("Incorrect Username or Password!");
}
}
}
catch(Exception ex)
{
var exceptionDialog = new MessageDialog
{
Message = { Text = ex.ToString() }
};
await DialogHost.Show(exceptionDialog, "RootDialog");
}
}
I am getting the following error while connecting using LDAP
Connection.freeWriteSemaphore(-2): semaphore not owned by any thread
I am using the following code
public static bool Authenticate(string userName, string password)
{
//logger.Debug("Try to connect to LDAP to authenticate user with " + userName + "/***");
string uDN = ldapUserDN.Replace("$UID", userName);
bool flag = false;
LdapConnection ldapConn = new LdapConnection();
try
{
ldapConn.Connect(ldapServer, int.Parse(ldapServerPort));
ldapConn.Bind(uDN, password);
flag = ldapConn.Bound;
}
catch (Exception ex)
{
//logger.Error("Exception in Authenticate():", ex);
}
finally
{
ldapConn.Disconnect();
}
return flag;
}
I'm currently developing a dating site for a school project, and I'mm currently trying to make a log in feature for it. We are not supposed to use the automatic register and login feature.
Any contact we have with the database should go through the WCF service application. I know how to implement it without using the WCF, but I need to use it now, and I can't find this on Google after searching .
public bool login(string UserName, string PassWord, bool isActive = true) {
try {
DALDataContext db = new DALDataContext();
var qry = from m in db.tblUsers
where m.userName == UserName && m.password == PassWord && m.isActive == isActive
select m;
if (qry.Count() > 0) {
return true;
} else {
return false;
}
}
catch (Exception) {
return false;
}
}
That's how I made it, so this should work if I implement it in my web application
like this:
ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
protected void btnLoginUser_Click1(object sender, EventArgs e) {
try {
string UserName = txtUserName.Text;
string PassWord = txtPassWord.Text;
obj.login(UserName, PassWord);
if (true) {
Session["me"] = UserName;
Response.Redirect("~/MyProfile.aspx");
}
}
catch (Exception){
}
}
I've been working with this for hours, the register part of this works... so I'm doing something really wrong or something. I'm using Visual Studio 2010 and SQL Server 2008 R2.
[SOLVED]
this is how i solved it
protected void btnLoginUser_Click1(object sender, EventArgs e)
{
try
{
string UserName = txtUserName.Text;
string PassWord = txtPassWord.Text;
bool isActive = true;
if (obj.login(UserName, PassWord, isActive))
{
Session["me"] = UserName;
Response.Redirect("~/MyProfile.aspx");
}
else
{
lblErr.Text = "fail";
}
}
catch (Exception)
{
}
}
}
}
You are ignoring the return value of your login method:
obj.login(UserName, PassWord); // <-- returns true/false.
if (true) // <-- Why?
{
...
Did you mean to do
if (obj.login(UserName, PassWord))
{
Session["me"] = UserName;
Response.Redirect("~/MyProfile.aspx");
} ...
Suggest to return user from WCF service by name, like:
public tblUser login(string UserName);
In the client side you can retrieve user by name:
var user = obj.login(UserName);
if (user != null && user.password == txtPassWord.Text)
DoLogin();
else
ShowError();