我编写了一个简单的 PHP 应用程序 (MyApp),它允许用户使用 Evernote 的 PHP SDK 登录到他们的 Evernote 帐户。但是,在我的应用程序中,我想这样做:
- 用户批准 Evernote 登录
- MyApp 接收#1 的 requestToken、requestTokenSecret 等。
- MyApp 将 #2 存储到 cookie 中,然后
$_SESSION
- 当用户稍后返回我的网站时,MyApp 通过 cookie 将他们登录
是的,我知道这种基于 cookie 的登录是不安全的。然而,我的应用程序不存储敏感数据。最简单的方法是什么?这是我的尝试:
//if cookie
if (isset($_COOKIE['requestToken'])) {
$m = new mysqli(MYSQL_SERVER, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
$q = "SELECT uid FROM users WHERE token={$_COOKIE['requestToken']} and secret={$_COOKIE['requestTokenSecret']}";
// cookie matches db?
if ($result = $m->query($q)) {
$_SESSION['login']=TRUE;
$result->close();
}
else // no match
$_SESSION['login']=FALSE;
}
else { //no cookie - create
if (EverNoteLogin()) {
$year=time()+86400*365; //86400 = 1 day
setcookie('requestToken',$_SESSION['requestToken'],$year);
setcookie('requestTokenSecret',$_SESSION['requestTokenSecret'],$year);
}
}
建议改进版本
//if cookie
if (isset($_COOKIE['requestToken'])) {
//check db
$m = new mysqli(MYSQL_SERVER, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
$s=$m->prepare("SELECT uid FROM user WHERE token=? AND secret=?");
$s->bind_param('ss',$rt, $rs);
$rt=$_COOKIE['requestToken'];
$rs=$_COOKIE['requestTokenSecret'];
$s->execute();
$s->store_result();
$n=$s->num_rows;
//match db?
if ($n) {
if ($n==1) { // 1 match
$s->bind_result($uid);
$_SESSION['uid']=$uid;
$_SESSION['login']=TRUE;
}
else
$_SESSION['login']=FALSE; // >1 match not good
}else
$_SESSION['login']=FALSE;
}
else { //no cookie - create
if (EverNoteLogin()) {
$year=time()+86400*365; //86400 = 1 day
setcookie('requestToken',$_SESSION['requestToken'],$year);
setcookie('requestTokenSecret',$_SESSION['requestTokenSecret'],$year);
}
}