laravel csrf_token 在 wordpress 中使用 curl 获取 url 请求时不匹配

laravel csrf_token mismatch when getting url request using curl in wordpress

抱歉我的英语不好。我认为同样的问题但有不同的想法已经问过,但我的想法是不同的。我要问的是我已经使用 curl 请求在 wordpress 中编译了 laravel url。请查看我的代码以更好地理解我想说的内容。

<html lang="{{ config('app.locale') }}">
     <head>
        <!-- ImportInWordpressHeaderStart -->
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <meta name="csrf-token" content="{{ csrf_token() }}" />
        <title>{{ config('app.name', 'Laravel') }}</title>
        <!-- ImportInWordpressHeaderEnd -->
       </head>
   <body> .......
         //here is my complete html part ignore it.


    <!-- ImportInWordpressFooterScriptStart -->
    <script type="text/javascript" src="{{ asset('frontend/js/jquery-2.1.0.min.js') }}"></script>
    <script type="text/javascript">
    $("#login form").on('submit', function (e){
                e.preventDefault();

                $.ajax({
                    type: $(this).attr('method'),
                    url: $(this).attr('action'),
                    data: $(this).serialize(),
                    dataType: "json", ........... // the rest ajax code.

    <!-- ImportInWordpressFooterScriptEnd -->

代码的上半部分完全在 laravel 中,运行良好。现在看看我在 wordpress 主题页眉和页脚中做了什么。

<?php  
//Laravel Home url 
$url = "http://example.com/home";  
$ch = curl_init();  

// set URL and other appropriate options  
curl_setopt($ch, CURLOPT_URL, $url);  
curl_setopt($ch, CURLOPT_HEADER, 0);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  

// grab URL and pass it to the browser  
$output = curl_exec($ch);  

//Regular expression to excerpt the targeted portion  
preg_match('/<!-- ImportInWordpressFooterStart -->(.*?)<!--ImportInWordpressFooterEnd -->/s', $output, $footer);  
preg_match('/<!-- ImportInWordpressFooterScriptStart -->(.*?)<!-- ImportInWordpressFooterScriptEnd -->/s', $output, $script);
// close curl resource, and free up system resources  
curl_close($ch);  
?> 

<?php echo $footer[0]; 
      wp_footer();
      echo $script[0];
?>

现在在 laravel 中,当我点击登录时,它是完美登录的,但是当我尝试在 wordpress 中做同样的事情时,它给我 令牌不匹配错误

 http://example.com/wordpress

wordpress 和 laravel 都在同一个域中,我不想在 wordpress 中再次创建相同的 laravel 页眉页脚。任何更好的想法将不胜感激。谢谢

每个 cookie session 都有自己的 csrf 令牌,您似乎没有尝试将 curl 收到的 cookie session id 传输到浏览器,或者 vise-versa.因此浏览器将尝试使用它自己的 cookie session 和 curl 的 cookie session 的 csrf 令牌登录,这绝对行不通。

解决方案:使 curl 使用浏览器的 cookie 获取 csrf 令牌。

$str='';
foreach($_COOKIE as $n=>$v){
    $str.=$name.'='.$v.'; ';
}
curl_setopt($ch,CURLOPT_COOKIE,$str);
  • 请注意,如果您获取 csrf 令牌的页面发送任何新的 Set-Cookie headers,curl 不会将这些 headers 传输到浏览器,除非您写一些代码来明确地做到这一点。例如,如果你获取 cookie session 的 url 也重新生成浏览器的 session id,并且你不将新的 id 传输到浏览器,它将有效地注销浏览器.