1

我在网上找不到我要找的东西,所以任何帮助都将不胜感激。我已经实现了一个自定义登录表单,用户在其中输入他的电子邮件和密码进行登录。然后我使用这些凭据查询数据库(密码经过哈希处理和加盐),如果两者都找到,那么我将 UserID 存储在会话状态中。如果用户关闭浏览器,则会话丢失,因此他必须重新登录。我了解了如何使用 cookie 来实现“记住我”功能,但我不知道我应该在 cookie 中存储什么以用于自动登录过程并使其安全。

PS:我知道 cookie 是什么以及它是如何工作的。我也知道不建议将用户凭据(电子邮件 + 密码)存储在 cookie 中。我正在使用带有 C# 的 asp.net 4.0

实际上,我正在寻找使用 cookie 的自动登录系统背后的逻辑。

谢谢!

4

3 回答 3

3

您应该只使用FormsAuthentication来设置 cookie:

FormsAuthentication.SetAuthCookie(theUserID, true); 

然后把它拿回来:

string userId = HttpContext.Current.User.Identity.Name;

如果您担心安全性,您可以考虑仅使用安全 cookie(您将只能通过 https 读取该 cookie)。

在相关帖子中有更多信息:ASP .Net 中的手动访问控制

更新:根据您的评论,您认为您不能在自定义登录表单中设置表单身份验证 cookie。所以我创建了一个空白的 ASP.NET 4 项目,在那里我创建了一个自定义登录——它将登录任何未经身份验证的用户。以下是三个部分:

(您的项目应该有类似的web.config东西,因为您的网站上有一个人们登录的表单):

<authentication mode="Forms"></authentication>

代码正面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="emptyWebApp._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     Username: <asp:Label ID="_username" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

后面的代码:

using System;
using System.Web;
using System.Web.Security;

namespace emptyWebApp
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                _username.Text = HttpContext.Current.User.Identity.Name;
            }
            else
            {
                _username.Text = "Not logged in";
                FormsAuthentication.SetAuthCookie("CookieMan", true);
            }
        }
    }
}

如您所见,您可以FormsAuthentication.SetAuthCookie在自己的自定义身份验证功能中设置身份验证 cookie,即使是像这样不合理的。

在这种情况下,当他们第一次点击页面时,它会显示Username: Not logged in,然后它会将他们作为“CookieMan”登录。刷新页面将显示Username: CookieMan

于 2013-02-17T18:19:39.940 回答
0

每当我这样做时,我只是组成一些随机的“SessionId”guid 并使用该值。

如果您的代码可以保留列表 sessionId/UserId 对并根据需要使它们过期。

于 2013-02-17T16:35:35.993 回答