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.

23 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/

  9. ssrvnzlgq says:

    спасибо интересное чтиво

  10. bentley says:

    My name is Regan Hackett. And I am a professional Content writer with many years of experience in writing.

    My interest is to solve problems related to writing. And I have been doing it for many years. I have been with several organizations as a volunteer and have assisted people 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 passionate writer who started at an early age.
    I’m happy that I`ve already sold several copies of my books in different countries like Canada and China and others too numerous to mention.
    I also work in a company that provides assistance to many students from different parts of the world. Students always come to me because I work no matter how complex their projects are. I help them to save energy, because I feel happy when people come to me for professional help.

    Academic Writer – Regan Hackett – TOP 5 MOST BEAUTIFUL SUNSETS IN EUROPE Corp

  11. I was wondering if you ever thought of changing the page layout of your site?
    Its very well written; I love what youve got to say. But
    maybe you could a little more in the way of content
    so people could connect with it better. Youve got an awful lot of text for only having one or two pictures.

    Maybe you could space it out better?

  12. philip says:

    Hello everyone , I’m Philip.
    Welcome to my website . I started writing in middle school after a creative writing assignment for my English teacher. I did creative writing for almost a year before I thought about doing something else.
    I had always loved doing non-fiction writing because I’m passionate about learning. When you combine writing talent with a love of learning, dissertation writing only makes sense as a job.
    I’m passionate about aiding the students of the future in their school career. When they don’t like their assignment , I am there to help.

    Philip Flowers – Writing Expert – iowafoodsystemscouncil.orgCompany

  13. Generationrdz says:

    bride, Julie d’Angenne.

  14. Holographiccpz says:

    and was erased, and on cleaned

  15. Telecastergrj says:

    European glory, and even after

  16. Yamahamhq says:

    scroll. Go to Code Form

  17. Seriesdem says:

    Since the era of Charlemagne

  18. Independentxhn says:

    ancient and medieval Latin,

  19. Haywardifv says:

    elements (case, binding).

  20. Fortresswxd says:

    From many manuscripts of Antiquity

  21. Focusham says:

    Western Europe also formed

  22. Rigidbbq says:

    Manuscript is a collective name for texts

Leave a Reply to Kevingop

*