简体   繁体   English

在2个选项卡中工作时如何修复会话过期 - Laravel 5.7

[英]How to fix session expired when working in 2 tabs - Laravel 5.7

I'm using Laravel 5.7, and use Auth system (from php artisan make:auth).Supposing in browser i have 2 tabs. 我正在使用Laravel 5.7,并使用Auth系统(来自php artisan make:auth)。在浏览器中我有2个标签。 In first tab, i set a button use ajax to send request to server and response success, but when open the second tab and do logout (or login) then comeback to the first tab (without reload first tab) try to do with button to send request, response now is error 419 status. 在第一个选项卡中,我设置了一个按钮,使用ajax向服务器发送请求并响应成功,但是当打开第二个选项卡并执行注销(或登录)然后返回第一个选项卡(不重新加载第一个选项卡)尝试使用按钮来发送请求,现在响应是错误419状态。

I think, there are some problem with session expired. 我认为会话过期有问题。 I searched but nowhere make me feel good. 我搜索但无处可让我感觉良好。

// tab 1

// front-end js
$("#button").click(function(){
   $.ajaxSetup({
      headers: {
        "X-CSRF-TOKEN": $("meta[name='csrf-token']").attr("content")
      }
  });
  $.ajax({
    url: "{{ route('test.post') }}",
    type: "post",
    dataType: "json",
    success: function(response){
        console.log(response);
    },
    error: function(){
        alert("error");
    }
 });
});

//server code
    public function post(Request $request){
        if(Auth::check()){
            return response()->json(["test" => 1]);
        }else{
            return response()->json(["test" => 0]);
        }
    }
// first click in tab 1: working normal
// turn on another tab a do log out or log in
// comeback tab 1 and click button: error with 419 status code ???

Now I want after login or logout in another tab then i can still click button working normal. 现在我想在登录或退出另一个选项卡后,我仍然可以点击按钮工作正常。 If can't, are there any solution to keep connect to server by ajax, axios...(something like that)... to update data in front end. 如果不能,是否有任何解决方案,以通过ajax,axios ...(类似的东西)保持连接到服务器...更新前端的数据。 Thank you much 非常感谢你

Laravel uses csrf tokens to protect your application from cross-site request forgery (CSRF) attacks. Laravel使用csrf令牌来保护您的应用程序免受跨站点请求伪造(CSRF)攻击。 Every session has new csrf-token. 每个会话都有新的csrf-token。 In your case you are using 2 tabs, on second tab you do login and logout. 在您的情况下,您使用2个选项卡,在第二个选项卡上,您可以登录和注销。 So after login/logout your csrf-token expired for the tab 1, you have to refresh that tab, so you can get new csrf-token for the session. 因此,在登录/注销后,csrf-token对于选项卡1已过期,您必须刷新该选项卡,以便为会话获取新的csrf-token。 Or you can exclude your route from csrf protection https://laravel.com/docs/5.8/csrf#csrf-excluding-uris just add your route in app/Http/Middleware/VerifyCsrfToken $except array. 或者你可以从csrf保护中排除你的路由https://laravel.com/docs/5.8/csrf#csrf-excluding-uris只需在app / Http / Middleware / VerifyCsrfToken $中添加你的路由除了数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM