Reputation: 145
I've been working on adding the "Remember Me" feature to my ASP.NET web application, but I've encountered an issue. When I check the "Remember Me" checkbox, it doesn't seem to work as expected. I've done some research and implemented the following code snippets:
In my login page: snippets from login.aspx
<tr>
<td>Remember me</td>
<td>
<asp:CheckBox ID="chkRememberMe" runat="server" />
</td>
<td></td>
</tr>
<td>
<asp:Button ID="btnSignIn" runat="server" Text="Sign In" OnClick="btnSignIn_Click" ValidationGroup="signin"/></td>
<td colspan="2">
<asp:CustomValidator ID="cusValWrongLogin" runat="server" ErrorMessage="The user name or the password (or both) are incorrect."></asp:CustomValidator>
</td>
</tr>
snippets from login.aspx.cs
private void manageCookieInfo()
{
// Retrieve the authentication cookie
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
// Decrypt the authentication ticket stored in the cookie
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
// Check if the authentication ticket is not expired
if (!authTicket.Expired)
{
string encryptedUsername = authTicket.Name;
string username = DecryptUsername(encryptedUsername);
txtusername.Text = username;
chkRememberMe.Checked = true;
}
else
{
// Uncheck the "remember me" checkbox if no cookie is found
chkRememberMe.Checked = false;
}
}
}
protected void btnSignIn_Click(object sender, EventArgs e)
{
try
{
string username = txtusername.Text.ToString();
string password = txtpassword.Text.ToString();
string btnText = btnSignIn.Text;
string storedPassword = (contact.Rows[0][18]).ToString();
bool validated = VerifyHashedPassword(password, storedPassword);
int saltLength = SaltValueSize * UnicodeEncoding.CharSize;
// Strip the salt value off the front of the stored password.
string saltValue = storedPassword.Substring(0, saltLength);
string hashedPassword = HashPassword(password, saltValue);
int userID = MyApp.DataService.Contact.SelectLogin(username, hashedPassword);
if (!btnText.Contains("Change") && userID > 0 && validated) // authenticated
{
if (Request.QueryString["ReturnUrl"] == null)
{
Session["FromLogin"] = "Yes";
}
Session["User"] = username;
Session["LoginFirst"] = "Yes";
MyApp.DataService.Contact.UpContactupdateType(userID, 1);
// Storing the password in a cookie
if (chkRememberMe != null && chkRememberMe.Checked == true)
{
// Timeout in minutes (30 days)
int timeout = 43200;
// Encrypt the username
string encryptedUsername = EncryptUsername(username);
var ticket = new FormsAuthenticationTicket(encryptedUsername, false, timeout);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Set the values of the custom cookies
HttpCookie userIdCookie = new HttpCookie("userid");
userIdCookie.Value = encryptedUsername;
userIdCookie.Expires = DateTime.Now.AddMinutes(timeout);
userIdCookie.HttpOnly = true;
userIdCookie.Secure = true;
Response.Cookies.Add(userIdCookie);
HttpCookie pwdCookie = new HttpCookie("pwd");
pwdCookie.Value = encryptedTicket;
pwdCookie.Expires = DateTime.Now.AddMinutes(timeout);
pwdCookie.HttpOnly = true;
pwdCookie.Secure = true;
Response.Cookies.Add(pwdCookie);
}
else
{
Response.Cookies["userid"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["pwd"].Expires = DateTime.Now.AddDays(-1);
}
if (Request.QueryString["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage(username, false);
}
else
{
FormsAuthentication.RedirectFromLoginPage(username, false);
Response.Redirect("~/Portal/default.aspx", false);
}
}
}
catch (Exception ex)
{
Response.AppendToLog("***** Exception during login ***** " + ex.StackTrace);
}
}
private string EncryptUsername(string username)
{
// Encryption using Base64 encoding
byte[] usernameBytes = Encoding.UTF8.GetBytes(username);
string encryptedUsername = Convert.ToBase64String(usernameBytes);
return encryptedUsername;
}
private string DecryptUsername(string encryptedUsername)
{
// Decryption using Base64 decoding
try
{
byte[] encryptedUsernameBytes = Convert.FromBase64String(encryptedUsername);
string username = Encoding.UTF8.GetString(encryptedUsernameBytes);
return username;
}
catch (FormatException)
{
// Handle invalid Base64 string error
return string.Empty;
}
}
I want to make sure that the username is remembered when the user logs out, but I'm facing issues with this part. Can someone help me identify what might be going wrong or if there's anything missing in my implementation?
In my logout page:
public partial class Logout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LogoutUser();
}
private void LogoutUser()
{
// Perform logout operations
// Sign out the user
System.Web.Security.FormsAuthentication.SignOut();
// Clear the authentication cookies
if (Request.Cookies["userid"] != null)
{
HttpCookie useridCookie = new HttpCookie("userid");
useridCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(useridCookie);
}
if (Request.Cookies["pwd"] != null)
{
HttpCookie pwdCookie = new HttpCookie("pwd");
pwdCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(pwdCookie);
}
// Clear the session
Session.Clear();
Session.Abandon();
// Redirect to the login page or any other desired page
Response.Redirect("~/Login.aspx");
}
}
web config
<authentication mode="Forms">
<forms name="Cookie" loginUrl="~/Login.aspx" protection="All" timeout="20" path="/" defaultUrl="portal/default.aspx"/>
</authentication>
Upvotes: 1
Views: 51