Codeigniter authentication library 1/3
Intro: safe cookies
Website security is becoming more and more important to every web developer. I wanted to write a simple yet secure authentication library for Codeigniter that would not need a lot of resources. By writing this article I will guide you through the thinking and coding process.
What we want is a secure way to authenticate users and identify users that are logged in using cookies. The first thing I did was to search the internet for existing examples out of curiosity. This showed me that a lot of those scripts are not secure. Cookies (and sessions) are not super-safe, there are ways to manipulate the values stored in cookies to bypass login scripts.
An example I have seen is to create a cookie that contains 2 values: 'userid' and 'loggedin'. Cookie values are stored on your computer as plain text and are easily adjusted. Creating a login script using only these 2 fields will make your site very vulnerable.
There are ways to protect you from users manipulating the cookie values. Codeigniter allows you to use a sessions database table rather than storing session information in a cookie. This is very safe because users can not view nor edit the information stored inside this sessions table. But using a database for session information can result in quite a lot of extra queries, especially when there are a lot of changes going on in the session information.
You can combine the database with caching solutions like memcache. This will reduce the number of queries but not everyone has the possibility to use memcache on his (shared) webserver.
I want to create a safe cookie that contains a specific token generated by the library that will tell if the user is logged in or not. While looking at some hash functions I stumbled on an interesting function called 'hash_hmac':
This hash function is a specific construction for calculating a message authentication code involving a cryptographic function in combination with a secret key. In the image above you see that SHA1 is used as the cryptographic function which will generate a 160 bit value. Using other cryptographic functions like SHA2 will result in a stronger code with a 256 bit value.
Part 2
Read the next part by clicking here