Storing more information using FormsAuthentication.SetAuthCookie

前端 未结 5 560
旧巷少年郎
旧巷少年郎 2020-11-30 20:45

I am using aspx and c# for a setting a authentication cookie for a login.

FormsAuthentication.SetAuthCookie(UserName, True)

I want to stor

5条回答
  •  粉色の甜心
    2020-11-30 20:53

    You can store additional information in the UserData property of the FormsAuthenticationTicket:

    using Newtonsoft.Json;
    using System.Web;
    using System.Web.Security;
    
    public class LoggedInUser
    {
        public string FirstName { get; set; } = null;
        public bool IsAdmin { get; set; } = false;
    }
    
    public static class Authentication
    {
        static void SignIn(
            HttpContextBase context,
            string emailAddress,
            bool rememberMe,
            LoggedInUser user = null)
        {
            var cookie = FormsAuthentication.GetAuthCookie(
                emailAddress.ToLower(),
                rememberMe);
            var oldTicket = FormsAuthentication.Decrypt(cookie.Value);
            var newTicket = new FormsAuthenticationTicket(
                oldTicket.Version,
                oldTicket.Name,
                oldTicket.IssueDate,
                oldTicket.Expiration,
                oldTicket.IsPersistent,
                JsonConvert.SerializeObject(user ?? new LoggedInUser()));
    
            cookie.Value = FormsAuthentication.Encrypt(newTicket);
    
            context.Response.Cookies.Add(cookie);
        }
    
        static void SignOut(HttpContextBase context)
        {
            FormsAuthentication.SignOut();
        }
    
        static LoggedInUser GetLoggedInUser()
        {
            if (HttpContext.Current.User?.Identity?.Name != null && HttpContext.Current.User?.Identity is FormsIdentity identity)
                return JsonConvert.DeserializeObject(identity.Ticket.UserData);
    
            return new LoggedInUser();
        }
    }
    

    Further Reading: https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/introduction/forms-authentication-configuration-and-advanced-topics-cs#step-4-storing-additional-user-data-in-the-ticket

提交回复
热议问题