Laravel 5 CSRF global token hidden field for all forms in a page

前端 未结 6 1961
迷失自我
迷失自我 2020-12-01 23:24

I recently migrated to Laravel 5, and now CSRF check is on every post submission. I thought about removing it but I want to follow the best practices, so I\'ll keep it that

6条回答
  •  既然无缘
    2020-12-01 23:59

    You need to pass along the header X-XSRF-TOKEN which contains an encrypted version of the csrf-token.

    There are two ways which this can be done that I am aware of. You can encrypt the token and pass it along to the view:

    $xsrfToken = app('Illuminate\Encryption\Encrypter')->encrypt(csrf_token());
    
    return view('some.ajax.form.view')->with('xsrf_token', $xsrfToken);
    

    Or you can grab the token from cookies using JavaScript (Angular makes this easy). In vanilla JS you might do something like this:

    function getCookie(name) {
        var pattern = RegExp(name + "=.[^;]*")
        matched = document.cookie.match(pattern)
        if (matched) {
            var cookie = matched[0].split('=')
            return decodeURIComponent(cookie[1])
        }
        return false
    }
    

    In jQuery you might then do something like this for the ajax request:

    $.ajax({
        // your request
        //
        beforeSend: function(request) {
            return request.setRequestHeader('X-XSRF-TOKEN', getCookie('XSRF-TOKEN'));
        }
    });
    

提交回复
热议问题