我无法在网上找到我正在寻找的东西,所以任何帮助都将不胜感激。 我已经实现了一个自定义登录表单,用户输入他的电子邮件和密码进行登录。然后我使用这些凭据查询数据库(密码是哈希和盐渍的),如果两者都找到,那么我存储了处于会话状态的UserID。如果用户关闭浏览器,则会话丢失,因此他必须再次登录。 我学会了使用cookie来实现“记住我”功能,但我不知道我应该在cookie中存储什么以进行自动登录过程并使其安全。
PS:我知道cookie是什么以及它是如何工作的。我也知道不建议将用户凭据(电子邮件+密码)存储在cookie中。 我正在使用带有C#的asp.net 4.0
实际上我正在寻找使用cookie的自动登录系统背后的逻辑。
谢谢!
答案 0 :(得分:2)
您应该使用FormsAuthentication来设置Cookie:
FormsAuthentication.SetAuthCookie(theUserID, true);
然后把它拿回来:
string userId = HttpContext.Current.User.Identity.Name;
如果您担心安全性,可以考虑仅使用安全cookie(您只能通过https读取该cookie)。
相关帖子中有更多相关信息:Manual Access control in 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,即使是一个非常合理的身份验证Cookie。
在这种情况下,当他们第一次点击页面时,它会显示Username: Not logged in
,然后它会将它们记录为“CookieMan”。刷新页面将显示Username: CookieMan
。
答案 1 :(得分:1)
我找到了关于这个问题的非常好的文章。我建议你们全部阅读!
答案 2 :(得分:0)
每当我这样做时,我只需要编写一些随机的“SessionId”guid并使用该值。
如果您的代码可以保留列表sessionId / UserId对并在必要时使它们到期。