ASP.NET Web 表单应用程序:实现“记住我”功能时遇到问题 - 需要指导

ASP.NET Web Form Application: Trouble Implementing 'Remember Me' Feature - Need Guidance

提问人:Snooper_A 提问时间:9/14/2023 更新时间:9/14/2023 访问量:17

问:

我一直在努力将“记住我”功能添加到我的 ASP.NET Web 应用程序中,但我遇到了一个问题。当我选中“记住我”复选框时,它似乎没有按预期工作。我做了一些研究并实现了以下代码片段:

在我的登录页面中: 登录 .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>

登录中的片段.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;
    }
}

我想确保在用户注销时记住用户名,但我遇到了这部分的问题。有人可以帮助我确定可能出了什么问题,或者我的实现中是否缺少任何内容吗?

在我的注销页面中:

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 配置

<authentication mode="Forms">
            <forms name="Cookie" loginUrl="~/Login.aspx" protection="All" timeout="20" path="/" defaultUrl="portal/default.aspx"/>
</authentication>
C# asp.net 身份验证 Cookie 表单身份验证

评论

0赞 VDWWD 9/15/2023
登录时的“记住我”可能并不意味着您认为的意思。当您登录、关闭浏览器并在您仍然登录的第二天再次返回时,会使用这些术语。但是您似乎想在用户注销时将用户名存储在 cookie 中?这应该是可能的,但我认为问题在于.这样可以防止将 cookie 写入浏览器(如果我没记错的话,网络表单已经有一段时间了。Response.Redirect

答: 暂无答案