views:

56

answers:

1

I'm just getting into learning about sessions, and for my purposes, I want to create something that upon every request from the client, the server authenticates that user, and only then performs data-handling for that user.

However, I have seen a lot of examples with CodeIgniter where the session is set up as thus:

$this->load->library('session');

$newdata = array(
               'username'  => 'johndoe',
               'email'     => '[email protected]',
               'logged_in' => TRUE
           );

$this->session->set_userdata($newdata);

However, couldn't someone just create a cookie on their computer with a common username and the 'logged_in' state to true, and suddenly you're authenticated without a password? This seems like a security flaw to me, but I see so many examples like this.

What is the proper way to authenticate the user on each request?

+1  A: 

In the application/config/config.php file of your codigniter install you can choose to encrypt your cookies.

$config['sess_cookie_name']  = 'ci_session';
$config['sess_expiration']  = 7200;
$config['sess_encrypt_cookie'] = TRUE;  // set from false to TRUE

Once this is set the set_userdata() and userdata() methods will transparently handle encrypting and decrypting the session data.

A full list of codigniter session config options is at the bottom of this page:

http://codeigniter.com/user_guide/libraries/sessions.html

DRL
Alright, that sounds good. The only thing I wonder is this as secure as storing session data in a database? If someone cracks the cookie encryption, they can now forge a cookie for any user (guessing usernames) instead of just accessing one user's account.
Nick
If it is a concern, why don't you use the database to store sessions? This way you can validate session ID's in addition to having the cookie encrypted. If you are concerned with security, you indeed *should* be using the database. See *Saving Session Data to a Database* section of the CI user guide: http://demos.softaculous.com/CodeIgniter/user_guide/libraries/sessions.html
stormdrain