总结FormsAuthentication的使用

一、先看一下使用FormsAuthentication做登录认证的用法

用法一:

FormsAuthentication.SetAuthCookie(username, isPersistent);

用法二:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    username,
    DateTime.Now,
    DateTime.Now.AddMinutes(720),
    isPersistent,
    userData,
    FormsAuthentication.FormsCookiePath);
 
// 加密票证
string encTicket = FormsAuthentication.Encrypt(ticket);
 
// 创建cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
HttpContext.Current.Response.Cookies.Add(cookie);

二、几个问题

1.用法一和用法二区别?

2.用法一中的认证过期时间是如何设置的?用法二中又是如何设置的?

3.用法二中票证中设置过期时间和Web.config中设置的过期时间哪个优先?

4.用法二中userData是否可以为null?

5.用法中的isPersistent是什么?

6.什么是持久化cookie?什么是会话性cookie?

7.用法二中的isPersistent为何没起作用?

三、解答

1.用法一无法使用userData数据。

2.用法一中的过期时间为Web.config中配置的时间。

3.用法二中票证中设置的过期时间优先于Web.config中设置的过期时间(即以票证中设置的过期时间为准)。

4.用法二中userData不可为null,否则无法加密票证。详见MSDN文档。

5.isPersistent表示是否要持久化认证cookie。

6.持久化cookie保存在物理介质中。(win7中的位置为C:Users用户名AppDataRoamingMicrosoftWindowsCookies,注意Appdata是个隐藏的文件夹)

会话性cookie保存于内存中。关闭浏览器则会话性cookie会过期消失;持久化cookie则不会,直至过期时间已到或确认注销。

注意:如果要使用会话性cookie,就不能为cookie对象设置过期时间,一旦设置了过期时间就为持久化cookie。

7.其实用法二是大家常见的写法,但这种写法并没有使isPersistent。参考以下写法:

public static void SetFormsAuthentication(string username, bool isPersistent, string userData)
{
    userData = string.IsNullOrEmpty(userData) ? string.Empty : userData;
 
    //创建票证
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
        username,
        DateTime.Now,
        DateTime.Now.AddMinutes(720),
        isPersistent,
        userData,
        FormsAuthentication.FormsCookiePath);
 
    // 加密票证
    string encTicket = FormsAuthentication.Encrypt(ticket);
 
    // 创建cookie
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
    {
        HttpOnly = true,
        Path = FormsAuthentication.FormsCookiePath,
        Secure = false
    };
    if (ticket.IsPersistent)
    {
        cookie.Expires = ticket.Expiration;
    }
    HttpContext.Current.Response.Cookies.Add(cookie);
}
原文地址:https://www.cnblogs.com/sjqq/p/7599362.html