dongzhi4498 2012-07-13 16:04
浏览 16
已采纳

如何验证是否是授权用户发送请求?

I'm stuck in this situation where I need to validate if it's the right user sending the request/information to the server. For example, a user submits a delete friend request, in the URL as parameters I include the friend's id (another member id); should I also include the member asking for the friend delete request's id?

I'm just trying to validate or make sure it's the right user sending the request. What's the best way to go about this in general? If the user is logged in can we just validate by logged in member's id? Or is there a better way?

  • 写回答

3条回答 默认 最新

  • dougao1542 2012-07-13 16:10
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法