FormsAuthenticationTicket

FormsAuthenticationTicket

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security; namespace WebAppTest.Controllers
{
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
return View();
} /// <summary>
/// 模拟登陆
/// 票据中的数据经过加密,解决了cookie的安全问题。
/// </summary>
/// <param name="username"></param>
public ActionResult Login()
{
WebUserData User = new WebUserData()
{
UserName = "wolf",
Age = ,
Area =
};
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(, User.UserName, DateTime.Now, DateTime.Now.AddMinutes(), false, Newtonsoft.Json.JsonConvert.SerializeObject(User));
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie newCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Domain = FormsAuthentication.CookieDomain,
Path = FormsAuthentication.FormsCookiePath
};
Response.Cookies.Add(newCookie);
return RedirectToAction("Index");
}
/// <summary>
/// 退出登录
/// </summary>
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index");
}
/// <summary>
/// 取得票据中数据
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult GetUserData()
{
HttpCookie cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
return Json(Newtonsoft.Json.JsonConvert.DeserializeObject<WebUserData>(ticket.UserData));
}
} public class WebUserData
{
public string UserName { get; set; }
public int Age { get; set; }
public int Area { get; set; } } }
05-11 01:18