Getting the current user id (not name) using forms authentication?

前端 未结 1 1548
青春惊慌失措
青春惊慌失措 2021-01-03 02:16

Question:

I\'m playing around with forms authentication and my own custom membership provider.

From what I see, I can get the current FormsIdentity by doing:

相关标签:
1条回答
  • 2021-01-03 03:19

    Yes, one can with a workaround from here.
    One can set the UserId in the Auth cookie-Ticket UserData.

    public class UserData
    {
        public string FirstName { get; set; }
        public UserData()
        {
            FirstName = "Unknown";
        }
    } // End Class UserData
    
    
    
    public void SignIn(string userName, bool createPersistentCookie)
    {
        if (String.IsNullOrEmpty(userName)) 
            throw new ArgumentException("Der Wert darf nicht NULL oder leer sein.", "userName");
    
        UserData userData = new UserData();
        SetAuthCookie(userName, createPersistentCookie, userData);
        //FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
    }
    
    
    public void SetAuthCookie(string userName, bool createPersistentCookie, UserData userData)
    {
        HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie);
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
        FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
             ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration
            ,ticket.IsPersistent, userData.ToJSON(), ticket.CookiePath
        );
    
        string encTicket = FormsAuthentication.Encrypt(newTicket);
        cookie.Value = encTicket;
        System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
    } // End Sub SetAuthCookie
    

    Another possibility is to just use the UserId.ToString() as "name".

    0 讨论(0)
提交回复
热议问题