Jump to content

Is this cookie auth code secure?


fred12ned

Recommended Posts

Is the following code secure when it is set to a cookie for cross-session authentication?

private function GenerateAuthKey($userid){	
$ip = $_SERVER['REMOTE_ADDR']; 
$user_agent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ""; 
$authkey = base64_encode(sha1(md5($this->GetDBPassword($userid) . $ip . $user_agent . time())));
$query = $this->db->buildquery("INSERT INTO member_session VALUES(%USERID%, '%AUTHKEY%', '%IP%', '%USERAGENT%', %EXPIRES%)", array("USERID" => $userid, "AUTHKEY" => $authkey, "IP" => $ip, "USERAGENT" => $user_agent, "EXPIRES" => time() + 30*24*60*60);
$this->db->query($query);
return $authkey;
}

private function ValidAuthKey($userid, $authkey){
$query = $this->db->buildquery("SELECT * FROM member_session WHERE user_id = %USERID% AND session_key = '%SESSION_KEY%'", array("USERID" => $userid, "AUTHKEY" => $authkey);
$result = $this->db->query($query);
if($result->num_rows){
	$ip = $_SERVER['REMOTE_ADDR']; 
	$user_agent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ""; 

	$row = $result->fetch_assoc();
	if($row['ip'] != $ip){
		return false;
	}elseif($row['user_agent'] != $user_agent){
		return false;	
	}elseif($row['expires'] < time()){
		return false;	
	}else{
		return true;	
	}				
}else{
	return false;	
}
}

Link to comment
https://forums.phpfreaks.com/topic/202581-is-this-cookie-auth-code-secure/
Share on other sites

The PHP session system only works for that browser session, so when you close the browser it ends.

 

No, not necessarily. Only if you use the default settings. You may change the lifetime of the session cookie using the session.cookie_lifetime php.ini directive. You can set this (and other settings) using session_set_cookie_params.

 

If you want it in a database (or somewhere else) instead, you can also use session_set_save_handler to accomplish that.

 

Persisting logins are needed in virtually all applications, and that's why there is built-in support for it in PHP. That way everybody don't have to reinvent it all the time.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.