Storing more information using FormsAuthentication.SetAuthCookie

前端 未结 5 568
旧巷少年郎
旧巷少年郎 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条回答
  •  猫巷女王i
    2020-11-30 21:04

    You can put whatever you want in the auth cookie as long as it's useful to you. That said, if you're putting sensitive information you should, at the very least, encrypt it, but I'd recommend against putting sensitive information there. You can do something like:

    Forms.SetAuthCookie (UserName + "|" + UserId, true);
    

    Then, whenever you need the username or the user id, it is there. Just load the cookie and parse out the values you need.

    Again, I'd advise against doing this, especially as I have it presented above. That said, it is possible. You should create accessor methods to pull the data back out:

    public int CurrentUserId
    {
        get
        {
            int userId = 0;
    
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                userId = Convert.ToInt32(HttpContext.Current.User.Identity.Name.Split('|')[1]);
            }
    
            return userId;
        }
    }
    
    public string CurrentUserName
    {
        get
        {
            string userName = string.Empty;
    
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                userName = HttpContext.Current.User.Identity.Name.Split('|')[0];
            }
    
            return userName;
        }
    }
    

提交回复
热议问题