user16010521
user16010521

Reputation:

Laravel Sanctum 'Access-Control-Allow-Origin' Error

I'm working on a Laravel 11 project where I'm using Laravel Sanctum for authentication in my SPA (Vuejs3). My setup includes a backend and a frontend hosted on different subdomains, and I'm running everything using Docker. The backend is accessible at http://shop_backend.localhost:8084 and the frontend at http://shop_frontend.localhost:8787.

When I try to make a request to the backend to get the CSRF cookie using Axios, I'm encountering a CORS error:

Access to XMLHttpRequest at 'http://shop_backend.localhost:8084/api/csrf-cookie' from origin 'http://shop_frontend.localhost:8787' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Despite this configuration, I still get the CORS error. What am I missing or doing wrong? Any help or pointers would be appreciated :)

I've already added the necessary CORS configuration in config/cors.php on the backend, but the issue persists. Here is my current CORS configuration:

.env

APP_NAME=SHOP
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://shop_backend.localhost:8084
FRONTEND_URL=http://shop_frontend.localhost:8787

APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US

APP_MAINTENANCE_DRIVER=file
APP_MAINTENANCE_STORE=database

BCRYPT_ROUNDS=12

LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shop
DB_USERNAME=test
DB_PASSWORD=test

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=.localhost

BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database

CACHE_STORE=redis
CACHE_PREFIX=

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379

SANCTUM_STATEFUL_DOMAINS=shop_frontend.localhost:8787

config: app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->statefulApi();
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

cors.php

<?php

return [
    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => [env('FRONTEND_URL')],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,
];

sanctum.php

<?php

use Laravel\Sanctum\Sanctum;

return [

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS')),

    'guard' => ['web'],

    'expiration' => 120,

    'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),

    'middleware' => [
        'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
        'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
        'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
    ],

    'prefix' => 'api',
];

docker-compose.yaml

volumes:
  redis_data:

services:
  database:
    image: mysql:8.4
    container_name: mysql_shop
    environment:
      - MYSQL_DATABASE=shop
      - MYSQL_USER=user
      - MYSQL_PASSWORD=test
      - MYSQL_ROOT_PASSWORD=test
    volumes:
      - /var/backups/mysql8/shop:/var/lib/mysql
    ports:
      - "3306"

  app:
    container_name: shop_backend
    image: webdevops/php-nginx:8.3-alpine
    volumes:
      - .:/var/www
      - ./docker/nginx/main.conf:/opt/docker/etc/nginx/main.conf
    ports:
      - "8084:80"
    links:
      - database
      - redis
    working_dir: /var/www
    hostname: shop_backend.localhost
    environment:
      - "DB_PORT=3306"
      - "DB_HOST=database"
      - "DB_PASSWORD=test"
      - "DB_DATABASE=shop"
      - "REDIS_ENDPOINT=redis"

  node:
    container_name: shop_frontend
    image: node:lts
    working_dir: /app
    command: bash -c "npm i && npm run dev -- --port 8080 --host"
    volumes:
      - ../shop-frontend:/app
    ports:
      - "8787:8080"
    user: node
    hostname: shop_frontend.localhost

  # phpmyadmin
  phpmyadmin:
    image: phpmyadmin
    restart: always
    depends_on:
      - database
    ports:
      - "8095:80"
    environment:
      PMA_USER: root
      PMA_PASSWORD: test
      PMA_HOST: database
      PMA_ARBITRARY: 1

  redis:
    image: redis:alpine
    restart: unless-stopped
    volumes:
      - redis_data:/data

I modified the Sanctum and CORS settings multiple times, but I continue to encounter the same error.

Upvotes: 0

Views: 203

Answers (0)

Related Questions