drh78568 2012-11-10 14:29
浏览 37
已采纳

如何修复ajax安全性?

There is a way to inject code via ajax or to fake information?

Like to send Ajax from my website to another website that use ajax?

If so how can I prevent this that I can send ajax only from my website?

  • 写回答

1条回答 默认 最新

  • duanliaolan6178 2012-11-10 14:44
    关注

    You're probably looking for CSRF (cross-site request forgery) protection. The issue is that your site has no idea where AJAX requests are coming from. The generally accepted solution is to create a token that is sent from your site which is required to be sent along with AJAX requests.

    This token would be unique to a user session and output somewhere in the HTML of your page. This makes it challenging for other sites to capture this token.

    To give you the basic idea, you would do something like this:

    $_SESSION['csrf_token'] = md5(uniqid(rand(), TRUE));
    

    Then you could for example output this as a JavaScript variable

    <script>
    window.CSRF_TOKEN = '<?php echo $_SESSION['csrf_token']; ?>';
    </script>
    

    If you happen to be using jQuery, you can use ajaxSend() to add the token to each request

    $.ajaxSend(e, jqXHR, settings) {
      if (!settings.data) settings.data = {};
      settings.data['csrf_token'] = window.CSRF_TOKEN;
    }
    

    Finally, on the backend you would check that $_REQUEST['csrf_token'] ==$_SESSION['csrf_token']` to validate the request. It's generally a good idea for these tokens to be one-time use if possible. Storing the time the token was generated and making sure it's used within a reasonable time frame is also a good idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题