Welcome Guest, Not a member yet? Register   Sign In
Is it safe to use sessions for user validation?
#3

(06-16-2017, 03:19 PM)ronaldv Wrote: I have a website with user registration & login. On login, after username and password are validated, I create a session like this:

PHP Code:
$this->session->set_userdata('user_id'$user->id); 

and then in Controllers and Modals I use this data to validate or identify users:

PHP Code:
$user_id $this->session->userdata('user_id');

if (
$user_id == '') {
    // user has not logged in and shouldn't have access to user-area pages.  
 
   ...
}

$query "SELECT * FROM users WHERE user_id='" $user_id "' ..."

Is this method safe or good practice? Is it possible for malicious users to manipulate the session data?


There is so much to think about when authenticating users, that you are better off using somebody else's library if security matters. Depending on how you'e configured sessions, and who has access to the server, there is a small chance that somebody would be able to alter the session data. In your particular code, what if the value of user_id was changed to:
PHP Code:
$user_id "1 OR user_id = 2 OR user_id = 3"


If you're like a lot of people, your admin user might be user ID 1, am I right? The possibilities are endless though, as you've not escaped the query at all.

I like to use the session only for a session ID, and store that session ID in the user's database row. If CI says you have a valid session, and it matches the session ID of the user, then you can perform further queries to get other data you may need.

If you don't want to do a bunch or work, or use an existing authentication library, consider at least type casting $user_id, like this:

PHP Code:
// Always an integer
$user_id = (int) $user_id

And also learn how to write safe queries in CI:


PHP Code:
$sql 'SELECT * from users where user_id = ?';
$query $this->db->query$sql, [ $user_id ] ); 
Reply


Messages In This Thread
RE: Is it safe to use sessions for user validation? - by skunkbad - 06-16-2017, 06:13 PM



Theme © iAndrew 2016 - Forum software by © MyBB