Keeping Users Logged In

Published on September 26, 2011 | Filed Under Advice

Recently, I’ve been doing some work with login forms and maintaining site credentials.  There are several issues, which must be taken into account when you handle how a user accesses your website.  I wanted to take a moment and write a quick
blog about how I like to handle users on my website.

Database Setup

The first step to user management is to properly set up your database.  In SQL Server 2008, I like to use the following table definition:

Field Type Notes
UserID INT Auto-Incrementing integer.  Unique. Primary Key
Username NVARCHAR(50)  
Password NVARCHAR(35) An MD5 Hash is 32 characters. You can use whichever method to encrypt that you would like.
Admin BIT Is the user an administrator?
ChangePassword BIT Should the user be prompted to change their password when they login next time?
SessionID NVARCHAR(15) Randomly-generated ID used to verify that this is the correct user.

Accessing the database

How often should you query your database for user information?  I’d highly recommend getting yourself a server that can handle being called every time someone lands on your web page. This might seem like overkill, but it will do the job.  If you generate a Session ID, don’t let the fact that the cookie exists be an indicator that the user is logged in.  What if your user is on one computer and a hacker is on another computer with an old Session ID?  If you’ve programmed your website properly, you can easily make 10+ calls to a database without any drag in performance.

The next time you’re on a major website such as your bank, or even Facebook, look at how much information is displayed on the page and try to imagine how many calls were made to the database to grab that information.  You should figure that it makes those calls for every single user that’s online at that time.

Cookies

I’m sure that there is a lot of debate on the topic of what you should hold in your cookie information.  The general consensus is that less is more.  Basically, if you know that you can handle authentication with just one cookie, then be my guest.  Personally, I like to use two cookies: Username and SessionID.  However, when I’m working on a small project that can only be accessed internally, I don’t mind just using SessionID.

Note: Do not store a user’s password in the cookie information; even if you’re storing a hashed
version. There is enough software out there to sniff cookies and decrypt many popular encryption algorithms that you’re opening yourself up to a major security hole if you decide to store that in a cookie.

Session IDs

I’ve spoken about the Session ID, but I didn’t really discuss how to generate them.  There really isn’t a specific way to do this. It’s all up to your imagination. I like to be case-sensitive with these, so I make sure to make Case-Sensitive Calls to SQL
when I have to verify the information. As for the original generation, I just use a random number generator and break my ASCII characters up into groups:

ASCII Range Character Range
48 – 57 0 – 9
65 – 90 A – Z (Uppercase)
97 – 122 a-z (Lowercase)

So the theory is as follows:

  • Randomly pick a number (0-2)
  • If 0: Choose 0-9 Range
    • Randomly Pick a number (48-57)
  • If 1: Choose A-Z Range
    • Randomly Pick a number (65-90)
  • If 2: Choose a-z Range
    • Randomly Pick a number (97-122)

Then you just build your string from there.  The logic isn’t too intense, but for the sake of this article, I won’t post any real code; I’d like to keep it generic.

Wrapping Up

I think my theories are fairly straight-forward.  I always welcome combating arguments.  If you have any suggestions or concerns, please feel free to share them in the comments below.

9 Responses to “Keeping Users Logged In”

  1. hawkeye says:

    Great post … Very very helpful

  2. MBJeffrey says:

    Hi, you need affordable taxation services?
    Visit our website today click here

  3. Kevingop says:

    companies that produce generic lipitor buy brand zoloft online lexapro generic markings lioresal buy does effexor xr come in generic accutane buy uk why was viagra originally invented hydrea 500 mg capsule price suprax liquid cost To acquire land large enough to buildschools would be very difficult, sir, it not impossible. I also despise reading a cheery, slightly humorous book and having a horrendously appalling plot element dropped like a bomb- with no real value to the story. A blockbuster movie followed. In this design, the polyethylene of the tibial component is attached firmly to the metal implant beneath. The SS soon placed a huge order for the gas with a German pest-control firm, an ominous indicator of the comingHolocaust. How I do it is if I enjoy a book, I go back and I work out why I enjoyed it. And now the world Wells made is on the brink of a global disaster that our “true” timeline has, so far, failed to experience… Also, if you like this book Read Human Genetics.

  4. jackall says:

    I’m an expert writer who loves to bring smiles to people’s face.

    Writing is what I do for a living and I am so passionate about this. I have worked with several associations whose mission is to help people solve problems.
    I love traveling and have visited several countries in the past few years.
    I’m happy to have written several books that have contributed positively to the lives of many. My books are available in several parts of the world. And I’m currently working with companies that help people save time. Being a part of this team has open more opportunities for me to excel as a writer. I have worked with different people and met many clients as a writer.
    I can handle any kind of writing project and provide nothing but the best. People come to me all the time to ask if I can solve their assignment problems and I accept. I find pleasure in assisting them to solve their problems as a writer.

    Academic Writer – Jack – //www.ipohrun.com/]Ipohrun Corps

  5. Uplotnitel says:

    Изготовление магнитного уплотнителя для холодильных и винных шкафов любой модели

    Мы изготовим профиль магнитного уплотнителя из высококачественных материалов и установим его в короткие сроки на любые модели:

    - бытовых холодильников всех моделей любого года выпуска;
    - торговых морозильных и кондитерских витрин;
    - морозильных ларей отечественного и импортного производства;
    - холодильных шкафов и камер шоковой заморозки;
    - любых советских холодильников.

    С нами интересно работать, так как у нас:

    - Собственное производство;
    - Высокое качество изделий;
    - Изготовление изделия на заказ за 24 часа;
    - Бесплатный вызов замерщика;
    - Профессиональный монтаж с гарантией;
    - Адекватная ценовая политика;
    - Специальные цены для мастеров по ремонту;
    - Скидки пенсионерам и постоянным клиентам;
    - Доставка по всей России.

    Кроме того, мы занимаемся обслуживанием:

    - физических и юридических лиц;
    - предприятий пищевой промышленности;
    - продуктовых магазинов и супермаркетов;
    - ресторанов, кафе и баров;
    - отелей, гостиниц и пансионатов;
    - компаний гарантийного ремонта холодильников.

    Добро пожаловать на наш сайт: https://xn--80aanbkcescrdedmxzcl4pmc.xn--p1ai/katalog/aeg/

  6. cyrusam says:

    My name is Cyrus Amos. And I am a professional academic writer with many years of experience in writing.

    My main focus is to solve problems related to writing. And I have been doing it for many years. I have been with several groups as a volunteer and have assisted in many ways.
    My love for writing has no end. It is like the air we breathe, something I cherish with all my being. I am a full-time writer who started at an early age.
    I’m happy that I`ve already sold several copies of my works in different countries like France and others too numerous to mention.
    I also work in an organization that provides assistance to many people from different parts of the world. Students always come to me because I work no matter how difficult their projects are. I help them to save money, because I feel fulfilled when people come to me for professional help.

    Academic Writer – Cyrus – //www.schoolratingsusa.com/]Schoolratingsusa Corp

  7. antinjaM says:

    оформить займ на карту онлайн: https://citycredits.com.ua/alexcredit/

  8. manykjaM says:

    онлайн займы на кошелек круглосуточно без отказа: https://citycredits.com.ua/alexcredit/

Leave a Reply

*