0

我陷入了这种情况,我需要验证是否是正确的用户将请求/信息发送到服务器。例如,用户提交删除好友请求,在 URL 中作为参数我包含好友的 id(另一个成员 id);我还应该包括要求朋友删除请求 ID 的成员吗?

我只是想验证或确保发送请求的是正确的用户。一般来说,最好的方法是什么?如果用户已登录,我们可以仅通过登录成员的 ID 进行验证吗?或者,还有更好的方法?

4

3 回答 3

2

Without knowing how your authentication works, it's a little difficult to say.

When I've had to do this in the past, I've used a combination of server-side authentication to identify the user sending the request, and URL parameters to specify what they want to delete. A user needs to be logged in to send a Delete request, and I'm tracking their userID with a $_SESSION variable. So when I get a Delete request, the SQL looks vaguely like:

DELETE FROM 
    friends 
WHERE 
    userID=$_SESSION["id"] AND friendID=$_POST["friend"]

As halfer explains in the comments, this is a generally bad way of doing things, as it opens an SQL injection vulnerability in the code. You can consider a couple of ways of avoiding that.

Firstly, you can sanitize the data - if you know that your friendID is always going to be an integer, you can check for that. A regular expression to check for non-numeric characters will work - if there's anything dodgy in there, you can deal with it appropriately and not pass it to the database.

The second approach is the one I prefer - when you make your query, you can use a prepared statement, and bind the parameters to it. Using PDO, you'll end up with something that looks like:

$sth = $dbh->prepare('DELETE FROM friends WHERE userID=? AND friendID=?');
$sth->bindParam(1, $_SESSION["id"]);
$sth->bindParam(2, $_POST["friend"]);
$sth->execute();
于 2012-07-13T16:10:49.933 回答
0

Try to require more secure UUID identifiers (generated and stored by you) for such requests, they are still not completely secure but considerably better than simple ids

于 2012-07-13T16:11:47.997 回答
0

使用会话变量来存储登录的用户 ID。一旦建立了会话并且您的身份验证方案插入了logged in您所有设置的标志。logged in当您需要执行任何用户请求时,只需检查标志。

于 2012-07-13T16:08:42.460 回答