This has been a tough moment as I am trying to achieve a login concept in my project, with authentication and authorization.
Basically, I had this login code where 3 things were achieved.
- The login code checks whether input email with password match the database record
- Login code checks if account has been activated
- The login code Updates “LastLogin” and “IsActive” columns in the table
If all these things checked are correct, then login takes place.
So, I decided to use authentication in the login, because I learnt it’s the best and standard way of validation. But in the new code, with validation when I click on the login nothing happens. I don’t know what the issues is, and why it does nothing.
This is my old login code
<div class="container-fluid">
<br />
<h2 class="form-signin-heading" style="color: #355171; text-align: center; font-weight: 500; font-size: 13pt; margin-top: -4px;">LOGIN</h2>
<div id="dvMessage" runat="server" visible="false" class="alert alert-danger" style="margin-bottom: 1%;">
<strong><i class="fad fa-exclamation-square" aria-hidden="true" style="margin: 0 7px; font-size: 13pt;"></i> </strong><asp:Label ID="lblMessage" runat="server" />
</div>
<label for="txtUsername" style="font-weight: 500;">Email</label>
<asp:TextBox ID="txtUsername" runat="server" CssClass="form-control" Font-Size="11pt" placeholder="Email Address" Width="100%" />
<br />
<label for="txtPassword" style="font-weight: 500;">Password</label>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" CssClass="form-control" Font-Size="11pt" placeholder="Password" />
<a href="https://quirver.com/RecoverPassword" style="color: #075481; float: right; text-decoration: none; font-size: 10pt;">Can't Remember my Password</a>
<br />
<br />
<asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" BackColor="#32657c" Text="Login" OnClick="Button1_Click" />
<br />
<br />
</div>
This is my new login
protected void Button1_Click(object sender, EventArgs e)
{
dvMessage.Visible = false;
lblMessage.Visible = false;
if (!string.IsNullOrEmpty(txtUsername.Text) & !string.IsNullOrEmpty(txtPassword.Text))
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security = True");
string check = "SELECT Uid FROM Users WHERE pass = @pass COLLATE SQL_Latin1_General_CP1_CS_AS AND email = @email AND pass = @pass";
SqlCommand com = new SqlCommand(check, con);
con.Open();
com.Parameters.AddWithValue("@email", txtUsername.Text.Trim());
com.Parameters.AddWithValue("@pass", Encrypt(txtPassword.Text.Trim()));
string Uid = Convert.ToString(com.ExecuteScalar());
con.Close();
if (!string.IsNullOrEmpty(Uid))
{
string users = "";
using (SqlCommand cmd = new SqlCommand("SELECT Uid FROM UserActivation WHERE Uid = @Uid"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Uid", Uid);
cmd.Connection = con;
con.Open();
users = Convert.ToString(cmd.ExecuteScalar());
con.Close();
}
if (string.IsNullOrEmpty(users))
{
int user = 0;
using (SqlCommand cmd = new SqlCommand("SELECT Uid FROM Users WHERE pass = @pass COLLATE SQL_Latin1_General_CP1_CS_AS AND email = @email AND pass = @pass"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@email", txtUsername.Text.Trim());
cmd.Parameters.AddWithValue("@pass", Encrypt(txtPassword.Text.Trim()));
cmd.Connection = con;
con.Open();
user = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
if (user > 0)
{
Session["user"] = user;
con.Open();
string query = "SELECT LastLogin, IsActive from Users WHERE Uid = @Uid";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@Uid", Session["user"]);
Session["LastLogin"] = Convert.ToDateTime(cmd.ExecuteScalar());
}
string UpdateLog = @"UPDATE Users SET LastLogin=@dateandtime, IsActive=@IsActive WHERE Uid = @Uid";
using (SqlCommand cmd = new SqlCommand(UpdateLog, con))
{
cmd.Parameters.AddWithValue("@dateandtime", DateTime.UtcNow);
cmd.Parameters.AddWithValue("@IsActive", "1");
cmd.Parameters.AddWithValue("@Uid", Session["user"]);
cmd.ExecuteNonQuery();
}
con.Close();
}
Session["user"] = user;
Response.Redirect("overview.aspx?Id=" + user);
}
else
{
dvMessage.Visible = true;
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Account has not been activated";
txtPassword.Text = "";
txtPassword.Focus();
}
}
else
{
dvMessage.Visible = true;
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Invalid Login Details";
txtPassword.Text = "";
txtPassword.Focus();
}
}
else
{
dvMessage.Visible = true;
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "All Fields are Required";
}
}
private string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
<div class="container-fluid">
<br />
<h2 class="form-signin-heading" style="color: #355171; text-align: center; font-weight: 500; font-size: 13pt; margin-top: -4px;">LOGIN</h2>
<div id="dvMessage" runat="server" visible="false" class="alert alert-danger" style="margin-bottom: 1%;">
<asp:Label ID="lblMsg" ForeColor="red" Font-Size="10" runat="server" />
</div>
<label for="txtUsername" style="font-weight: 500;">Email</label>
<input id="txtUserName" type="text" runat="server" class="form-control" style="font-size: 11pt;" placeholder="Email Address"/>
<asp:RequiredFieldValidator ControlToValidate="txtUserName" Display="Static" ErrorMessage="Field Required" ForeColor="Red" Font-Size="9pt" runat="server" ID="vUserName" />
<br />
<label for="txtPassword" style="font-weight: 500;">Password</label>
<input id="txtUserPass" type="password" runat="server" class="form-control" style="font-size: 11pt;" placeholder="Password"/>
<asp:RequiredFieldValidator ControlToValidate="txtUserPass" Display="Static" ErrorMessage="Field Required" ForeColor="Red" Font-Size="9pt" runat="server" ID="vUserPass" />
<a href="#" style="color: #075481; float: right; font-weight: 500; font-size: 10pt;">Can't Remember my Password</a>
<br />
Remember me: <asp:CheckBox ID="chkPersistCookie" runat="server" AutoPostBack="false" />
<br />
<input type="submit" value="Login" runat="server" class="btn btn-primary" id="CmdLogin" onclick="CmdLogin_ServerClick" style="background-color: #32657c;" /><p></p>
</div>
private bool ValidateUser(string email, string pass)
{
SqlConnection conn;
SqlCommand cmd;
string lookupPassword = null;
// Check for invalid userName.
// userName must not be null and must be between 1 and 15 characters.
if ((null == email) || (0 == email.Length) || (email.Length > 15))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
return false;
}
// Check for invalid passWord.
// passWord must not be null and must be between 1 and 25 characters.
if ((null == pass) || (0 == pass.Length) || (pass.Length > 25))
{
System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
return false;
}
try
{
// Consult with your SQL Server administrator for an appropriate connection
// string to use to connect to your local SQL Server.
conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\AuthenticationTestDatabase.mdf;Integrated Security = True");
conn.Open();
// Create SqlCommand to select pwd field from users table given supplied userName.
cmd = new SqlCommand("Select pass from Users where email=@email", conn);
cmd.Parameters.Add("@email", SqlDbType.NVarChar, 25);
cmd.Parameters["@email"].Value = email;
// Execute command and fetch pwd field into lookupPassword string.
lookupPassword = (string)cmd.ExecuteScalar();
// Cleanup command and connection objects.
cmd.Dispose();
conn.Dispose();
}
catch (Exception ex)
{
// Add error handling here for debugging.
// This error message should not be sent back to the caller.
System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message);
}
// If no password found, return false.
if (null == lookupPassword)
{
// You could write failed login attempts here to event log for additional security.
return false;
}
// Compare lookupPassword and input passWord, using a case-sensitive comparison.
return (0 == string.Compare(lookupPassword, pass, false));
}
private void CmdLogin_ServerClick(object sender, System.EventArgs e)
{
if (ValidateUser(txtUserName.Value, Encrypt(txtUserPass.Value)))
FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, chkPersistCookie.Checked);
else
Response.Redirect("Login.aspx", true);
}
private string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}