How to fix /sanctum/csrf-cookie errors

Viewed 4543

I am creating react js project with the Laravel Sanctum Axios API. When I get the sign-up page it shows the below error.

cors.php

<?php

return [

'paths' => ['api/*', 'sanctum/csrf-cookie','register', 'login' ],

'allowed_methods' => [ 
    'GET', 
    'POST', 
    'PUT', 
    'PATCH', 
    'DELETE', 
    'OPTIONS'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => [  
    'Origin',
    'Content-Type', 
    'Accept',
    'Authorization',
    'X-Requested-With',
    'X-CSRF-Token',
    
    ],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

];

Now below error shown Access to XMLHttpRequest at 'http://localhost:8000/sanctum/csrf-cookie' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field x-xsrf-token is not allowed by Access-Control-Allow-Headers in preflight response.

config/Session.php

<?php

use Illuminate\Support\Str;

return [

    'driver' => env('SESSION_DRIVER', 'file'),

  

    'lifetime' => env('SESSION_LIFETIME', 120),

    'expire_on_close' => false,  
    'encrypt' => false,

    'files' => storage_path('framework/sessions'),

  
    'connection' => env('SESSION_CONNECTION', null),

    
    'table' => 'sessions',

 
    'store' => env('SESSION_STORE', null),

   
    'lottery' => [2, 100],

    'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),

 

    'path' => '/',

    'domain' => env('SESSION_DOMAIN', null),

    'secure' => env('SESSION_SECURE_COOKIE'),

    'http_only' => true,

    'same_site' => 'lax',

];

.env file

APP_NAME="Crafty Shop"
APP_ENV=local
APP_KEY=base64:ECzTCbd8nfS6I82jRsd4sj4Bo6yJa0GRTfyTOrOoCno=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3310
DB_DATABASE=crafty
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

app.js

axios.defaults.baseURL= "http://localhost:8000/";
axios.defaults.headers.post['Content-Type'] ='application/json';
axios.defaults.headers.post['Accept'] ='application/json';
axios.defaults.withCredentials = true;
axios.interceptors.request.use(function (config) {
    const token = localStorage.getItem('auth_token');
    config.headers.Authorization = token ? 'Bearer ${}':'';
    return config;
});

Login.js

axios.get('/sanctum/csrf-cookie').then(response => {
    axios.post('api/login',data).then(res =>{
        if(res.data.status === 200){
            localStorage.setItem('auth_token', res.data.token);
            localStorage.setItem('auth_name', res.data.username);
            swal("Success", res.data.message,"success");
            console.log(res.data.username);
            history.push('/');
      
        }
        else if(res.data.status === 401){
            swal("Warning", res.data.message,"warning");
        }
        else{
            setLogin({...loginInput,error_list:res.data.validation_errors});
        }
    });
});

Sanctum.php

<?php

return [

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
    ))),
   


    'guard' => ['web'],

   
    'middleware' => [
        'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
        'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
          'cors' => \App\Http\Middleware\CorsMiddleware::class,
    ],

];
2 Answers

You MUST enable CORS on your server app. Find out how Laravel does this.

This question may help you. Laravel CORS

You need to give access to your front localhost to send requests to the back-end API.

So I recommend you carefully follow the instructions from the laravel website: https://laravel.com/docs/8.x/sanctum#spa-configuration

and if you would have any questions about some steps you can ask me.

But I think your problem is that your front URL cannot send requests and you have to allow it. but anyway first you have to follow the steps from the link

Related