PHP User Authentication with Sessions

2019-04-16 10:29发布

问题:

So my question is very basic.

When checking if a user is still logged in on any page, I'll use

if (isset($_SESSION['user']) && $_SESSION['user'] == true) { CODE }

But, shouldn't I use a hashed value instead of a boolean value for the $_SESSION['user']? All the guides I find are using boolean values, but from my point of view that is a security leak, isn't it? People are talking about Session-Hjacking and Session-Fixation all the time, and that would be very easy if I just used boolean values for the user-session, woulnd't it? Or am I just mixing things up here?

Thank you

回答1:

I read two questions here. The first question, 'What is the best practice to determine if a user is logged in?" and the second question 'Is there a concern of Session-Hjacking and Session-Fixation?'

First question: Most web apps/cms I have worked with have a user object. There is nothing particular special about this object from a code perspective, its just an object representing the user. The currently logged in user has their user object stored in the session. $_SESSION['user']

In Drupal (and other platforms) the a function is used to return the currently logged in user, or False if the user is not logged in.

Example:

function user(){
 if( isset($_SESSION['user') and 
     is_object($_SESSION['user'] and 
     get_class($_SESSION['user']=='myUserClass')) ){

         return $_SESSION['user'];

     }else{
         return False;
      }
}

So in your example we see if ( user() ) { CODE } works because all object evaluate as True in an if clause.

Second Question: Session-Hjacking and Session-Fixation are not really concerns here. The client (a web browser) does not have access to the server's $_SESSION array. So in short, yes you are mixing things up here.