FormsAuthenticationTicket用法
FormsAuthenticationTicket :提供对使用 forms 身份验证用于确定用户身份的票证的属性和值的访问。 此类不能被继承。
其构造函数有三个:
FormsAuthenticationTicket(string name, bool isPersistent, int timeout);
name:与票证关联的用户名。
isPersistent: true 如果该票证将存储在持久性 cookie (保存在浏览器会话);,否则为 false。 如果该票证存储在 URL 中,则忽略此值。
timeout: 以分钟为单位,身份验证票证的有效时间。
FormsAuthenticationTicket(int version, string name, DateTime issueDate, DateTime expiration, bool isPersistent, string userData)
expiration:本地日期和票证的到期的时间。
issueDate: 本地日期和时间所颁发票证。
userData: 要存储在票证的特定于用户的数据。
FormsAuthenticationTicket(int version, string name, DateTime issueDate, DateTime expiration, bool isPersistent, string userData, string cookiePath);
cookiePath:票证存储在 cookie 中时的路径。
使用:
eg:
生成ticket
public ActionResult Index()
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
"hello",
DateTime.Now,
DateTime.Now.AddMinutes(30),
true, "chen"
);
string authTicket = FormsAuthentication.Encrypt(ticket);
//将加密后的票据保存为cookie
HttpCookie coo = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket);
HttpContext.Response.Cookies.Add(coo);
return View();
}
配置authentication web.config下system.web节点内添加
<authentication mode="Forms"> <forms loginUrl="~/Home/Index" defaultUrl="Admin.aspx" name=".ASPXFORMSAUTH"> </forms> </authentication>
验证是否拥有ticket
this.Request.IsAuthenticated
注消ticket
FormsAuthentication.SignOut();
获取ticket中的UserData:
如图:

适合用做登录模块, 写一个属性拦截器
public class myAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("HttpContext");
}
return (httpContext.Request.IsAuthenticated);
}
}
如下三个页面:
public ActionResult Index()
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
"hello",
DateTime.Now,
DateTime.Now.AddMinutes(30),
true, "chen"
);
string authTicket = FormsAuthentication.Encrypt(ticket);
//将加密后的票据保存为cookie
HttpCookie coo = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket);
HttpContext.Response.Cookies.Add(coo);
return View();
}
[my]
public ActionResult About()
{
ViewBag.Message = "Your application IsAuthenticated page.";
return View();
}
public ActionResult logout()
{
string strUserData = ((FormsIdentity)(HttpContext.User.Identity)).Ticket.UserData;
FormsAuthentication.SignOut();
ViewBag.Message = "Your contact page.";
return View();
}
其中,如果先访问Index,获取ticket 是可以访问About和logout,
然后访问logout,将ticket注销,再访问About时,会被拦截器阻止,跳转到web.config中配置的loginUrl,即index。
浙公网安备 33010602011771号