【发布时间】:2013-04-21 22:08:45
【问题描述】:
我正在创建一个使用两个会话的登录系统(对于那些不允许使用 cookie 的人(同意 cookie 法律..我正在使用该网站http://www.cookielaw.org/the-cookie-law.aspx作为参考)
现在,我有这个系统用于我的 cookie 身份验证
function GenerateString(){
$length = mt_rand(0,25);
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(5, strlen($characters) -1)];
}
return $string;
}
$RandomString = GenerateString();
$CookieAuth = $DB->prepare("INSERT INTO cookieauth (Username,RandomString) VALUES (?,?)");
$CookieAuth->bind_param('ss',$_POST['Username'],$RandomString);
$CookieAuth->execute(); // Insert the Authentication Methods into the database
$CookieAuth->close(); // Allow another query/statement
$GetInsertID = $DB->prepare("SELECT ID FROM CookieAuth WHERE RandomString=?");
$GetInsertID->bind_param('s',$Randomstring);
$GetInsertID->execute();
$GetInsertID->bind_result($RowID);
$GetInsertID->fetch();
$GetInsertID->close();
setcookie("Auth[ID]",$RowID);
setcookie("Auth[UName],$_POST['Username']);
setcookie("Auth[RandomString]",$RandomString);
然后处理cookie:
if(isset($_COOKIE['Auth'])){
$Authenticate = $DB->prepare("SELECT Username,RandomString FROM cookieauth WHERE ID=?");
$Authenticate->bind_param('i',$_COOKIE['Auth']['ID']);
$Authenticate->execute();
$Authenticate->bind_result($RowUsername,$RowString);
$Authenticate->fetch();
$Authenticate->close();
if ($_Cookie['Auth']['UName'] == $RowUsername){
if ($_COOKIE['Auth']['RandomString'] == $RowString){
header("Location: LoggedIn.php");
}else{
die("Possible Cookie Manipulation, Autologin Cannot Continue");
}
}else{
die("Possible Cookie Manupulation, Autologin Cannot Continue!");
}
我的总体目标是通过使用 cookie 提供自动登录功能。正如人们应该知道的那样,它们基本上以纯文本形式存储在硬盘驱动器上。所以如果我包含一个随机生成的字符串,每次进一步处理都会更改(然后更新 cookie 以匹配数据库)这是一种相当安全的方式完成任务?我的意思是,我知道这不是 100% 安全的,因为某些用户可能会尝试操纵随机字符串,所以我可以使用盐随机密钥,然后使用 hash_hmac 对盐 + 密钥进行 sha512 处理并将其保存为饼干...
我的总体问题是,我提供的块是否提供了一种半安全的方法来通过 cookie 处理自动登录,并且可以最大限度地减少一些坏人操纵密钥以获取所需数据的可能性?
【问题讨论】:
-
如果有人能猜出一个有效的 PHP 会话 ID(假设标准会话 ID 长度/复杂性设置),那么您就无法阻止他们。当 PHP 已经在生成随机代码时,生成自己的代码是没有意义的。
-
随机生成或密钥将更改网站每个条目上的cookie,更新我的数据库和cookie以匹配,每个用户行将不同,每个用户的每个密钥将不同..所以我猜想实现某种算法可能有助于提高安全性?
-
会话也可以这样做... session_regenerate_id()。您主要是在尝试重新发明轮子。
-
您可能会发现以下链接很有帮助:web.archive.org/web/20130214051957/http://jaspan.com/…
-
完全重复:stackoverflow.com/q/5459682/338665 或 stackoverflow.com/q/2336678/338665(我会将其标记为第二个)...
标签: php authentication cookies