doz22551 2016-09-20 20:51
浏览 45
已采纳

使用ajax和fetch API修改PHP v3 CSRF

i have set up the normal CSRF stuff etc and would work well, but then when i go and use ajax using the whatwg-fetch api (https://github.com/github/fetch)

Now all seem ok and all works well to what i have. BUT! Then I add the CSRF settings as below and it fails, all the time:

So, I have used the normal, but it fails and in the header I get the message: Failed CSRF check!

        $app->add(new \Slim\Csrf\Guard);

But I wanted to add own message etc so have added the following, but still it does not pass.

      $container['csrf'] = function ($c) {
          $guard = new \Slim\Csrf\Guard;
          $guard->setFailureCallable(function ($request, $response, $next) {
              $request = $request->withAttribute("csrf_status", false);
              return $next($request, $response);
          });
          return $guard;
      };

     $app->add($container->get('csrf'));

Then in my class i check it with:

      if (false === $req->getAttribute('csrf_status')) {...}else{//all ok}

But what ever happens it always fails.

in my js i am adding the token details to the request like:

    fetch('/post/url',{
       method: 'POST',
       headers: {
               'X-CSRF-Token': {
                       'csrf_name':csrf_name,
                       'csrf_value':csrf_value
                   }
           },
       body: new FormData(theForm)

i have looked in the posted data etc and the form data is submitted including the csrf values etc. SO the require csrf data is being sent via the form as well as the header?

So how can I get the ajax functionality to work with the Slim CSRF, what am I missing?

Thanks in advance

  • 写回答

4条回答 默认 最新

  • doujishan2247 2016-09-21 20:16
    关注

    well after several attempts over the last day and narrowing it down to the fetch api was using I decided to go back to the trusted jQuery aJax methods, and this seems to have worked.

    Seems the following body and the new FormData() was not being picked up:

    fetch('/post/url',{
       method: 'POST',
       body: new FormData(theForm)
    

    So switched it out for

         $.ajax({
               url : '/url/to/post',
               type: "POST",
               data: {key:value, kay:value}
    

    And all worked well.

    The next issue to look into then is the keys being refreshed on first ajax call, preventing anymore calls unless page is refreshed, but thats for another day

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加