Hello Forum,
I have been able to achieve user authentication on login, using the in-built default Login Tool in the Toolbox. But that is the default tool.
Is it possible to use authentication in my custom Login page?
Because I want to be able to pass user's details to display on every webpage the user navigates to.
Previously I was using Session to pass user details to web pages, but I discovered authentication and decided to try it out. Please if you could help me see where authentication can be added to this my code without using stored procedure or master page. I just want that after successful login user will be redirected to Home, while if Admin, he will be redirected to Admin page. Thank you.
Here are my Table
Users
Uid |
email |
pass |
Name |
LastLogin |
IsActive |
RoleId |
1 |
Admin@admin.com |
xxxxxxx |
Admin |
1/11/2023 11:04:52 PM |
0 |
1 |
2 |
Client@client.com |
xxxxxxxx |
Client |
1/11/2023 11:49:52 PM |
0 |
2 |
3 |
ClientUser@user.com |
xxxxxxx |
ClientUser |
1/11/2023 11:58:52 PM |
0 |
3 |
4 |
User@user.com |
xxxxxxxxx |
User |
1/12/2023 11:0:58 PM |
0 |
3 |
RolesTable
Uid |
RoleId |
1 |
Administrator |
2 |
ClientUserAdmin |
3 |
ClientUser |
HTML
<!-- Login starts-->
<div class="row" style="width: 100%; margin: 0 auto;">
<div class="col-sm-5" style="margin: 0 auto;">
<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="#" style="color: #075481; float: right; text-decoration: none; font-size: 10pt;">Forgotten Password?</a>
<br />
<br />
<asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" BackColor="#32657c" Text="Login" OnClick="ValidateUser" />
<br />
<br />
</div>
<br />
</div>
</div>
<!--Login ends-->
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//using the Identity IsAuthenticated method on login page load event to redirect user if not authenticated
if (this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
Response.Redirect("~/Login.aspx");
}
}
}
protected void ValidateUser(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUsername.Text) & !string.IsNullOrEmpty(txtPassword.Text))
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\QuirverData.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();
//checks to see if logi details are correct
if (!string.IsNullOrEmpty(Uid))
{
string users = "";
//checks to see if account has been activated
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)
{
//if account has been activated, it select lastlogin date and IsActive coulmns and updates them on login
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("Home.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)
{
//This encrypts the password
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;
}