-1

How can I set the XSRF-TOKEN in Laravel 8 on bootstrap.js.

According to the file it is being handled automatically but when i try to access the user data it returns unauthorized.

My bosstrap.js codes

window._ = require('lodash');

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo';

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     forceTLS: true
// });
  • AFAIK this should be coupled already out of the box. Do you experience a csrf issue? – Techno Sep 15 '22 at 14:56
  • CSRF token will not result in "Unauthorised" if missing. It will result in "session expired" I don't think your issue is a CSRF issue, it might be an auth issue – apokryfos Sep 15 '22 at 15:26
  • I am not experncing csrf issue – Tukei David Sep 16 '22 at 09:20
  • So maybe you can elaborate what issue you do experience(apperantly not csrf). In the world of programming it often happens that you have issue x but are asking for an answer to problem y(it is therefor called the xy problem), this results in people answereing the wrong question. The solutions people are providing are probably(thus far) incorrect because they are assuming things and not verifying. – Techno Sep 19 '22 at 11:27

2 Answers2

0

If you are using AJAX you can do this before any request:

    $.ajaxSetup({
    headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
    },
    });

Assuming that you have a meta tag in your blade view:

    <meta name="csrf-token" content="{{ csrf_token() }}">
GCesenas
  • 76
  • 4
0

If you are unable to get CSRF token from meta tag so you can prefix all routes under use vu by vu/ and exclude URIs from CSRF by simply adding them to the $except property of the VerifyCsrfToken middleware app/Http/Middleware/VerifyCsrfToken.php .

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'vu/*',
    ];
}

Documentation