I am making a login form using dapper library something is wrong here i cant seem to make it to work even if the password or username is wrong it opens up new form
if (string.IsNullOrEmpty(txtUsername.Text))
{
MessageBox.Show("Please enter your usernmae.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtUsername.Focus();
return;
}
try
{
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
var data = db.Query("select Username,Password from UserLog", commandType: CommandType.Text);
if ((data.SingleOrDefault() !=null)
{
MessageBox.Show("You have been succesfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
FormHome frm= new FormHome();
frm.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Your Username or Password is Incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You are simply sending this query to the database so it will return results every time irrespective of the login info:
select Username, Password from UserLog
So of course it will pass since you are not filtering the records. As long as you have 1 record in the database, it will pass.
You need to send the user login info and check if a record exists with the login info for the current user that you are trying to authenticate:
IEnumerable users = db
.Query("select Username, Password from UserLog where UserName = #UserName and Password = #Password",
new {UserName = txtUsername.Text, Password = // put the password here});
if (users.Any())
{
// authenticated so do whatever
}
Related
I have a problem with getting all the events from a remote computer.
try
{
string queryString = "*[System/Level=1 or System/Level=2 or System/Level=3 or System/Level=4 or System/Level=5]";
SecureString password = new NetworkCredential("", getPassword()).SecurePassword;
EventLogSession session = new("RemoteComputer", getDomainName(), getAdminName(), password, SessionAuthentication.Default);
password.Dispose();
EventLogQuery query = new("Application", PathType.LogName, queryString);
query.Session = session;
EventLogReader logReader = new(query);
EventRecord eventRecord;
while ((eventRecord = logReader.ReadEvent()) != null)
{
eventRecords.Add(eventRecord); //save records
}
//display records
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
The program is getting only some part of events from the remote computer and displays them, but then it throws an exception with message "Cannot find the specified file".
What's the problem and how can I get all the events?
I'm creating a LMS. It has a part which checks the username and password from the database and grants access but i dont know how to do that.here is the code.
{
if (uname.Text == "" || pass.Text == "")
{
MessageBox.Show("Fields cannot be left blank.");
}
else
{
if (uname.Text != "member")
{
MessageBox.Show("Username Incorrect.");
}
else if (pass.Text != "member")
{
MessageBox.Show("Password Incorrect");
}
else
{
Form3 frm = new Form3();
frm.Show();
}
Now here i need to change "member" to the values that i have entered in the password database.Here is the database
the database is successfully linked
how do i make read like if "username from my database"== myusername and same for password?
you can put query like this
Select * from passdb where username=#user and password=#pass;
for checking null fields you can put validators.
I am trying to check if the user is successfully logged in to Axosoft. The code bellow never throws an error, even if the user provides the wrong credentials.
public void Login(string user, string pwd)
{
try
{
AxoClient.ObtainAccessTokenFromUsernamePassword
(
username: user,
password: pwd,
scope: ScopeEnum.ReadWrite
);
}
catch (AxosoftAPIException<ErrorResponse> ex)
{
ErrorResponse er = new ErrorResponse();
er.Error = ex.Source;
er.ErrorDescription = ex.StackTrace;
er.Message = ex.Message;
throw new AxosoftAPIException<ErrorResponse>(er);
}
}
I found the solution for my problem.
After a login you can get the value of the HasAccessToken in Proxy.
If you successfully logged in it will return true, otherwise it'll return false.
Proxy AxoClient = new Proxy
{
Url = "http://url",
ClientId = "ClientId",
ClientSecret = "ClientSecret",
};
AxoClient.ObtainAccessTokenFromUsernamePassword
(
username: user,
password: pwd,
scope: ScopeEnum.ReadWrite
);
MessageBox.Show(AxoClient.HasAccessToken);
I hope this will help others.
On my login form after i save my content to SQL and if i try to get the information from the database the information passes the evaluation to true even if the information provided is typed both ways - upper case or lower case.Here is my login code,please help me understand.I'am contacting database with Entity Framework.the currUser is a variable where I save the current user information.
try
{
if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
{
var users = from c in context.CustomerTables where c.username == username && c.password == password select c;
List<CustomerTable> table = users.ToList();
if (table.Any())
{
MessageBox.Show("Successfully logged in.\nWelcome " + username + "!", "Welcome", MessageBoxButton.OK, MessageBoxImage.Asterisk);
currUser.username = username;
currUser.password = password;
return true;
}
else
{
MessageBox.Show("Username or password is invalid.", "Error logging in", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
}
else
{
MessageBox.Show("Username and password format is invalid!","Null username or password",MessageBoxButton.OK,MessageBoxImage.Warning);
return false;
}
The simplest fix would be to replace
if (table.Any())
with
if (table.Any() && table[0].username == username && table[0].password == password)
The reason why this would work is that string comparison in C# is case-sensitive by default.
I'm working on a Silverlight application that uses oracle security to authenticate the users. (This is a business requirement so it can't be changed).
I do so by calling a WCF web service that attempts to open a connection to the database using the provided username and password. If the connection fails, I catch the exception and return a message to the user, here's the login code:
[OperationContract]
public LoginResult LogIn(string username, string password, DateTime preventCache)
{
var result = new List<string>();
try
{
connectionString = ConfigurationManager.ConnectionStrings["SecurityBD"].ToString();
connectionString = connectionString.Replace("[username]", username);
connectionString = connectionString.Replace("[password]",passowrd)
using (var connection = new Oracle.DataAccess.Client.OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
return new LoginResult(true, GetPermisos(username), preventCache);
}
else
{
return new LoginResult(false, null, preventCache);
}
}
}
catch (Oracle.DataAccess.Client.OracleException ex)
{
if (ex.Number == 1017)
{
return new LoginResult(new SecurityError("Wrong credentials.", ErrorType.InvalidCredentials));
}
//Password expired.
if (ex.Number == 28001)
{
return new LoginResult(new SecurityError("Password expired.", ErrorType.PasswordExpired));
}
//Acount is locked.
if (ex.Number == 28000)
{
return new LoginResult(new SecurityError("Account is locked.", ErrorType.AccountLocked));
}
else
{
return new LoginResult(new SecurityError("An error occurred while attempting to connect." + Environment.NewLine + "Error: " + ex.ToString(), ErrorType.UndefinedError));
}
}
catch (Exception exg)
{
return new LoginResult(new SecurityError("An error occurred while attempting to connect." + Environment.NewLine + "Error: " + exg.ToString(), ErrorType.UndefinedError));
}
}
If the connection fails because of an expired password, I show the corresponding message to the user and then prompt him for his old and new password, and then send the new credentials to a ChangePassword method on my web serivce.
[OperationContract]
public ChangePasswordResult ChangePassword(string username, string oldPasswrod, string newPassword)
{
string connectionString = string.Empty;
try
{
connectionString = ConfigurationManager.ConnectionStrings["SecurityBD"].ToString();
connectionString = connectionString.Replace("[username]", username);
connectionString = connectionString.Replace("[password]",passowrd)
using (var connection = new OracleConnection(connectionString))
{
connection.Open();
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
using (var newConnection = new Oracle.DataAccess.Client.OracleConnection(connectionString))
{
newConnection.OpenWithNewPassword(Cryptography.TransportDecrypt(newPassword));
if (newConnection.State == System.Data.ConnectionState.Open)
{
return new ChangePasswordResult(null);
}
}
}
return new ChangePasswordResult(new SecurityError("Couldn't connect to the database.", ErrorType.UndefinedError));
}
}
catch (OracleException ex)
{
if (ex.Number == 1017)
{
return new ChangePasswordResult(new SecurityError("Wrong password", ErrorType.InvalidCredentials));
}
//Password expired.
if (ex.Number == 28001)
{
using (var newConnection = new Oracle.DataAccess.Client.OracleConnection(connectionString))
{
try
{
newConnection.OpenWithNewPassword(Cryptography.TransportDecrypt(newPassword));
if (newConnection.State == System.Data.ConnectionState.Open)
{
return new ChangePasswordResult(null);
}
else
{
return new ChangePasswordResult(new SecurityError("No se pudo establecer una conexión con la base de datos", ErrorType.UndefinedError));
}
}
catch (Oracle.DataAccess.Client.OracleException oex)
{
if (oex.Number == 28003)
return new ChangePasswordResult(new SecurityError("You'r new password does not match the security requeriments.." + Environment.NewLine + oex.Message, ErrorType.PasswordNotChanged));
else
return new ChangePasswordResult(new SecurityError(oex.Message, ErrorType.UndefinedError));
}
}
}
//Acount is locked.
if (ex.Number == 28000)
{
return new ChangePasswordResult(new SecurityError("Account is locked.", ErrorType.AccountLocked));
}
else
{
return new ChangePasswordResult(new SecurityError("Couldn't establish a connection." + Environment.NewLine + "Error: " + ex.Message, ErrorType.UndefinedError));
}
}
catch
{
throw;
}
}
After I perform the change password operation, the user is still able to connect with the old password and he's not able to connect with the new password. Only after I restart the application the change seems to take effect.
I'm using oracle's ODP.net driver. With Microsoft's oracle client, the user is able to connect with both the new and the old password after the password change.
The preventCache parameter was there only to verify that there was no type of client cache. I send the current date from the client, and then return the same value from the web service to see if it actually changes with subsequent requests, and it does as expected.
I've tried listening to the InfoMessage event of the connection, to see if there's any warning, but doing this prevents the password expired exception from being risen, and the code never reaches the eventHandler.
I'm completely lost, this behavior seems very odd to me and I still haven't figured out the root cause for the problem.
I've tryied copying the LogIn and ChangePassword methods on a desktop (WPF) application and it behaves exactly the same. So i guess the problem is not in the silverlight client.
Ok, i've figured this out. Checking with Toad the connection reminded opend even after executing the Connection.Close() method. This behavior seems to be part of the connection pooling mechanism from oracle.
Including Pooling=false on the connection string solved the problem.