FormsAuthenticationTicket

Posted 积少成多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 10,
                Area = 100
            };
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, User.UserName, DateTime.Now, DateTime.Now.AddMinutes(60), 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; }

    }


}

 

以上是关于FormsAuthenticationTicket的主要内容,如果未能解决你的问题,请参考以下文章

FormsAuthenticationTicket登录验证及票据和cookie过期

将 WebAPI JWT 访问令牌作为加密的 FormsAuthenticationTicket 存储在 Response.Cookies 中是不是安全(在 asp.net mvc 中)

关于ASP.NET MVC的权限认证的一些总结