65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET 中永久用户登录会话

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.77/5 (17投票s)

2011 年 10 月 9 日

CPOL

3分钟阅读

viewsIcon

101489

downloadIcon

7558

使用自定义 cookie 创建永久登录会话

引言

本文介绍如何在 ASP.NET 中创建永久用户登录会话。示例代码包括一个 ASP.NET MVC4 项目,用于控制用户注册和登录过程。但您可以在任何类型的 ASP.NET 项目中使用此技术。

表单身份验证

在深入探讨本文之前,您必须熟悉 ASP.NET 中的表单身份验证。 表单身份验证的配置位于 web.config 文件中,该文件具有以下带有赋值的配置文件片段。

<authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" 
             protection="All"
             timeout="1"
             name=".USERLOGINCONTROLAUTH"
             path="/"
             requireSSL="false"
             slidingExpiration="true"
             defaultUrl="~/Home/Index"
             cookieless="UseDeviceProfile"
             enableCrossAppRedirects="false"/></authentication>

默认值描述如下:

  • loginUrl 指向应用程序的自定义登录页面。 您应将登录页面放在需要安全套接字层 (SSL) 的文件夹中。 这有助于确保凭据从浏览器传递到 Web 服务器时的完整性。
  • protection 设置为 All 以指定表单身份验证票证的隐私和完整性。 这会导致使用 machineKey 元素上指定的算法对身份验证票证进行加密,并使用也在 machineKey 元素上指定的哈希算法对其进行签名。
  • timeout 用于指定表单身份验证会话的有限生存期。 默认值为 30 分钟。 如果颁发了持久表单身份验证 cookie,则 timeout 属性也用于设置持久 cookie 的生存期。
  • namepath 设置为应用程序配置文件中定义的值。
  • requireSSL 设置为 false。 此配置意味着身份验证 cookie 可以通过未进行 SSL 加密的通道传输。 如果您担心会话劫持,则应考虑将 requireSSL 设置为 true
  • slidingExpiration 设置为 true 以强制实施滑动会话生存期。 这意味着只要用户在网站上保持活动状态,会话超时就会定期重置。
  • defaultUrl 设置为应用程序的 Default.aspx 页面。
  • cookieless 设置为 UseDeviceProfile 以指定应用程序对所有支持 cookie 的浏览器使用 cookie。 如果不支持 cookie 的浏览器访问该站点,则表单身份验证会在 URL 上打包身份验证票证。
  • enableCrossAppRedirects 设置为 false,以指示表单身份验证不支持自动处理在查询字符串上或作为表单 POST 的一部分在应用程序之间传递的票证。

FormsAuthentication.SetAuthCookie 方法

此方法为提供的用户名创建一个身份验证票证,并将其添加到响应的 cookie 集合,或者如果您使用的是无 cookie 身份验证,则添加到 URL。 此函数的第一个重载有两个参数

  • userName: 经过身份验证的用户的名称
  • createPersisntentCookieTrue 创建持久 cookie(跨浏览器会话保存的 cookie);否则为 false

此方法将 cookie 或持久 cookie 添加到浏览器,并在 “timeOut” 参数中设置过期时间,在 “name” 和 “path” 参数中设置名称和路径。 一旦 cookie 过期,用户将自动注销。 因此,用户登录会话取决于保存在浏览器 cookie 中的表单身份验证票证的过期时间。 在这里,我将使用此技术创建一个永久用户登录会话。

Cookie 辅助程序

此类的功能是将表单身份验证票证添加到浏览器 cookie 集合,并具有生命周期到期时间。

public sealed class CookieHelper
{
    private HttpRequestBase _request;
    private HttpResponseBase _response;

    public CookieHelper(HttpRequestBase request, 
	HttpResponseBase response)
	{
		_request = request;
		_response = response;
	}

    //[DebuggerStepThrough()]
    public void SetLoginCookie(string userName,string password,bool isPermanentCookie)
    {
        if (_response != null)
        {
            if (isPermanentCookie)
            {
                FormsAuthenticationTicket userAuthTicket = 
                	new FormsAuthenticationTicket(1, userName, DateTime.Now, 
                	DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);
                string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
                HttpCookie userAuthCookie = new HttpCookie
                	(FormsAuthentication.FormsCookieName, encUserAuthTicket);
                if (userAuthTicket.IsPersistent) userAuthCookie.Expires = 
						userAuthTicket.Expiration;
                userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
                _response.Cookies.Add(userAuthCookie);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
            }
        }
    }
}

此函数在登录页面或控件上,在单击登录按钮时使用。 在附加的示例项目中,以下函数是在 AccountController 类中编写的。 此函数验证用户的登录,然后将永久表单身份验证票证添加到浏览器。

private bool Login(string userName, string password,bool rememberMe)
{
    if (Membership.ValidateUser(userName, password))
    {
        CookieHelper newCookieHelper = 
		new CookieHelper(HttpContext.Request,HttpContext.Response);
        newCookieHelper.SetLoginCookie(userName, password, rememberMe);
        return true;
    }
    else
    {
        return false;
    }
} 

关注点

因此,通过这种方式,您可以控制表单身份验证票证来控制用户的登录会话。

历史

  • 2011 年 10 月 9 日:初始发布
© . All rights reserved.