C# Store User Id and other information in Context.User.Identity

The Dot.net framework offers an excellent authentication function with it’s FormsAuthentication. But there is a small irritating limitation with it’s implementation.

 

If you are anything like me you do your own authentication and use a user id to specify an user in the database.
All of your code will depend on this id and you will need access to it in your website code. So you could store the id in the Identity.Name property but then you would also need to perform a query every time you need to get the displayname. A Common fix would be storing the information inside a session, this however is not without it’s flaws.
So what’s a quick alternative?

 

In this example I’ve put the user id and displayname in the Identity.Name property. The trick is to create one string and make use of a delimiter to split the values.
There are better way’s to do this, you could write a new Identity class. However this is a good quick alternative.

 

Sample code:
Login routine

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            int _LoginId = CheckLogin(edUsername.Text, edPassword.Text);
            if (_LoginId > 0)
            {
                FormsAuthentication.RedirectFromLoginPage(GetDisplayname(_LoginId) + '|' + _LoginId, cbRememberMe.Checked);
            }
            else
            {
                lblErrorMessage.Text = "Incorrect username password combination.";
            }
        }

Here is a sample on how to get the user id from the identity object.

        public static int GetUserId(HttpContext aContext)
        {
            if (aContext.User.Identity.IsAuthenticated)
            {
                string[] _values = aContext.User.Identity.Name.Split('|');
                return Convert.ToInt32(_values[1]);
            }
            else
                return 0;
        }

One thought on “C# Store User Id and other information in Context.User.Identity

Comments are closed.