我还没有为自己编写代码,但我会这样处理这个问题:
1.创建一个表,当用户为持久性提供 cookie 时,该表可用于强制进行有效性检查:
create table RememberMe
(
user_id int(10) NOT NULL,
user_token char(10) NOT NULL,
token_salt int(6) NOT NULL,
time int(10) NOT NULL,
PRIMARY KEY (user_id),
CONSTRAINT nameYourConstraint
FOREIGN KEY (user_id)
REFERENCES userTableName (whatever_user_id_equals)
)
要填充此表,我将在登录名中添加一些代码行,对于此示例,我将使用伪代码
// userID variable has been sanitized already so
// check if user clicked remember me
// and if the user logged in successfully:
if ( rememberMe == checked && login() == true )
{
// random number to serve as our key:
randomNumber = random( 99, 999999 );
// convert number to hexadecimal form:
token = toHex( ( randomNumber**randomNumber ) );
// encrypt our token using SHA1 and the randomNumber as salt
key = encrypt( token, randomNumber, SHA1 );
// get the number of seconds since unix epoch:
// (this will be 10 digits long until approx 2030)
timeNow = unix_time()
// check to see if user is in table already:
sql = "SELECT user_id FROM RememberMe
WHERE user_id = 'userID'";
// connect to database:
db = new DBCon();
result = db->query( sql );
// number of rows will always be 1 if user is in table:
if ( result->rows != 1 )
exists = true;
else
exists = false;
result->free_memory();
if ( exists == true )
{
sql = "UPDATE RememberMe SET
user_id = 'userID'
user_token = 'token'
token_salt = 'randomNumber'
time = 'timeNow'";
}
else
{
sql = "INSERT INTO RememberMe
VALUES( 'userID', 'token', 'randomNumber', 'timeNow' )";
}
result = db->query( sql );
// the affected rows will always be 1 on success
if ( result->affected_rows != 1 )
{
print( "A problem occurred.\nPlease log in again." );
quit();
}
result->free_memory();
// create a new cookie named cookiemonster and store the key in it:
// (we're not actually storing a score or birthday, its a false flag)
set_cookie( "CookieMonster", escape("score="+ userID +"birthday="+ key );
}
这段代码的作用是检查用户是否检查了记住我,并使用用户的键、令牌和盐以及时间填充数据库表(以便您可以对记住我实施时间限制特征)。
从这里您可以向您的网站添加代码,检查是否设置了CookieMonster cookie,如果设置了,您可以按照以下步骤强制执行其有效性:
从提供的 cookie 中提取用户 ID 和密钥
用userID查询数据库看是否
--> a) user has requested to be remembered
--> b) check the time to see if they cookie is still valid
--> c) extract the token and salt from database table record
通过 encrypt() 函数调用运行令牌和盐,并与提供的密钥匹配。
如果一切顺利,请创建一个新会话并让用户登录。
现在,每次用户访问您的站点时,他们都会登录,并且如果他们的计算机遭到入侵,攻击者将无法访问他们的密码
旁注:您应该始终要求您的用户在更改密码或电子邮件时提供密码,这样如果用户的 cookie 落入坏人之手,您的攻击者将无法窃取该帐户。