PHP会话var是否足以进行用户身份验证? [英] PHP session var enough for user auth?
问题描述
场景:
- 用户登录后,将设置一个会话变量以确认其登录.
- 在每个页面的顶部,确认登录会话变量有效
- 如果不是,则将其引导出去.
- 不使用持久性cookie,仅使用
session
- After a user has logged in, a session variable is set confirming their login.
- At the top of every page, login session variable is confirmed valid
- If it's not, they're booted out.
- No persistent cookies are used, only
session
问题:
这本身就是一种足够强大的安全措施,还是我应该
Is this a strong enough security measure by itself, or should I
- 设置两个会话变量以相互验证和/或
- 实施数据库/哈希验证
- ...?
========
(顺便说一句,当我研究此问题时,此Wiki 是一本很棒的书.)
(Incidentally, while I was researching this question, this wiki is a fantastic read.)
推荐答案
仅在会话中存储用户登录名(或用户ID)就足够了.
It is enough to store just user login (or user id) in the session.
要防止会话固定/劫持,您所需要做的只是实现简单的算法(伪代码):
To prevent session fixation/hijacking everything you need is just to implement simple algorythm (pseudocode):
if (!isset($_SESSION['hash']) {
$_SESSION['hash'] = md5(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'no ua');
} else if ($_SESSION['hash'] != md5(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'no ua')) {
session_regenerate_id();
$_SESSION = array();
$_SESSION['hash'] = md5(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'no ua');
}
您可以将哈希计算移到某些函数中以防止重复,我刚刚展示了可能的保护方法.
You could move the hash calculation into some function to prevent of duplication, i've just shown a sketch of possible protection.
这是我在kohana会话课程中实施这种保护的方式:
This is how I implemented this kind of protection in my kohana session class:
abstract class Session extends Kohana_Session
{
public function read($id = null)
{
parent::read($id);
$hash = $this->calculateHash();
$sessionHash = $this->get('session_fixation');
if (!$sessionHash) {
$this->set('session_fixation', $hash);
} elseif ($sessionHash != $hash) {
$this->regenerate();
$_SESSION = array();
$this->set('session_fixation', $hash);
}
}
private function calculateHash()
{
$ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
$ua = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'no ua';
$charset = !empty($_SERVER['HTTP_ACCEPT_CHARSET']) ? $_SERVER['HTTP_ACCEPT_CHARSET'] : 'no charset';
$ip = substr($ip, 0, strrpos($ip, '.') - 1);
return md5($ua . $ip . $charset);
}
}
这篇关于PHP会话var是否足以进行用户身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!