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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算