T
T
tol642020-06-26 15:51:15
Nginx
tol64, 2020-06-26 15:51:15

Laragon/Nginx + Laravel + Nuxt: 419 - CSRF token mismatch?

Please help me understand and solve the problem. A series of lessons based on the material: https://youtu.be/KFgi3IqavK4

Windows 10 OS

Project path:
C:\laragon\www\larastart-project

There are two folders in this directory:
C:\laragon\www\larastart- project\backend
C:\laragon\www\larastart-project\frontend

The first one (backend) has the Laravel framework installed .
The second (frontend) has the Nuxt framework installed . Laragon/Nginx

Settings : Contents of auto.larastart-project.test.conf file :

5ef5eb3419cb4459276935.png



server {
    listen 8080;
    listen 8443 ssl;
    server_name larastart-project.test *.larastart-project.test;
    root "C:/laragon/www/larastart-project/";
    
    index index.html index.htm index.php;
 
    location / {
    proxy_buffers 16 4k;
    proxy_buffer_size 2k;
    
    # npm run dev
    proxy_pass http://localhost:3000;
    
        # try_files $uri $uri/ /index.php$is_args$args;
    # autoindex on;
    }
  
    location /api {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    
    # php artisan serve
    proxy_pass http://localhost:8000/api;
    }
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass php_upstream;		
        #fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    # Enable SSL
    ssl_certificate "C:/laragon/etc/ssl/laragon.crt";
    ssl_certificate_key "C:/laragon/etc/ssl/laragon.key";
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
    ssl_prefer_server_ciphers on;
  
  
    charset utf-8;
  
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }
    location ~ /\.ht {
        deny all;
    }
}


Laravel Settings

Dependencies in composer.json . The Sanctum package is used for authentication : https://laravel.com/docs/7.x/sanctum#spa-authentication

"require": {
        "php": "^7.2.5",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^6.3",
        "intervention/image": "^2.5",
        "laravel/framework": "^7.0",
        "laravel/sanctum": "^2.4",
        "laravel/tinker": "^2.0",
        "spatie/laravel-medialibrary": "8.0.0"
    },
    "require-dev": {
        "barryvdh/laravel-ide-helper": "^2.7",
        "facade/ignition": "^2.0",
        "fzaninotto/faker": "^1.9.1",
        "laravel/ui": "^2.0",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^4.1",
        "phpunit/phpunit": "^8.5"
    },


.env file

APP_URL=http://localhost
CORS_ALLOWED_ORIGIN=http://localhost:3000
SANCTUM_STATEFUL_DOMAINS=http://localhost:8000
SESSION_DRIVER=file
SESSION_DOMAIN=localhost


File config\cors.php

return [
    'paths' => [
        'api/*',
        'login',
        'logout',
        'user',
        'sanctum/csrf-cookie',
    ],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];


File app\Http\Kernel.php

protected $middlewareGroups = [
...
        'api' => [
            EnsureFrontendRequestsAreStateful::class,
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];


Nuxt Settings

Dependencies in package.json

"dependencies": {
        "@nuxtjs/auth": "^4.9.1",
        "@nuxtjs/axios": "^5.3.6",
        "@nuxtjs/dotenv": "^1.4.1",
        "@nuxtjs/proxy": "^2.0.0",
        "bootstrap": "^4.5.0",
        "bootstrap-vue": "^2.15.0",
        "cookie-universal-nuxt": "^2.1.4",
        "iview": "^3.1.5",
        "jquery": "^3.5.1",
        "moment": "^2.27.0",
        "nuxt": "^2.0.0",
        "popper.js": "^1.16.1",
        "prismjs": "^1.20.0"
    },
    "devDependencies": {
        "node-sass": "^4.14.1",
        "nuxt-purgecss": "^1.0.0",
        "sass-loader": "^8.0.2"
    }


.env file

API_URL=http://localhost:8000/api
API_DOMAIN=http://localhost:8000


nuxt.config.js file . Settings related to authentication are shown.

...
    modules: [
        '@nuxtjs/axios',
        '@nuxtjs/auth',
        '@nuxtjs/proxy',
        '@nuxtjs/dotenv',
        'bootstrap-vue/nuxt',
        [
            'cookie-universal-nuxt', {
                alias: 'cookie'
            }
        ],
    ],
    auth: {
        strategies: {
            local: {
                endpoints: {
                    login: {
                        url: process.env.API_DOMAIN + '/login',
                        method: 'post'
                    },
                    logout: {
                        url: process.env.API_DOMAIN + '/logout',
                        method: 'post'
                    },
                    user: {
                        url: process.env.API_DOMAIN + '/user',
                        method: 'get',
                        propertyName: false
                    }
                },
                tokenRequired: false,
                tokenType: false
            }
        }
    },
    axios: {
        baseURL: process.env.API_DOMAIN,
        credentials: true
    },
...


We check the token request in the Postman program : https://www.postman.com/

It can be seen that the data is being returned.

5ef5ed1e63a95817778704.png

Next, we make a page with a test form: pages\auth\signin.vue Method

code:

methods: {
        async login() {
            try {
                await this.$axios.$get('http://localhost:8000/sanctum/csrf-cookie');
                await this.$auth.loginWith('local', {
                    email: this.form.email,
                    password: this.form.password,
                });
                this.$router.replace('/');
            } 
            catch (e) {
                this.errors = 'Could not sign you with these credentials.';
                console.log(e);
            }
        }
    }


Result:

5ef5ed5f42e84809764466.png

Details: There is no XSRF-TOKEN in the Cookies

5ef5ed848bf00901428271.png

5ef5eddeaf4dd818492828.png

5ef5ee01303d2912441857.png

list on the Application tab . It seems that it should also be here when submitting form data.

5ef5ee3304018391032231.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kami16ru, 2020-09-13
@kami16ru

Your request for csrf cookie returns ok.
1. Remove cookies from the browser
2. In laravel run the commands:

  • php artisan config:clear
  • php artisan cache:clear
  • php artisan config:cache

If you made changes to the cache, they may not always be cached due to permission problems (I still don’t understand why, I’m sinning on the IDE, which writes in files under root). It's best to always clear the cache after making changes in the config folder.
If, when performing these operations, you have an error with rights, in no case solve it by issuing rights 777 to this folder. Just manually delete the cache file that has root root permissions. You can check the permissions in the current directory with the command ls -la
3. axios: {
baseURL: process.env.API_DOMAIN,
credentials: true
},
In my opinion, you need withCredentials: true
4. async login() {
try {
await this.$axios. $get('localhost:8000/sanctum/csrf-cookie ');
await this.$auth.loginWith('local', {
email: this.form.email,
password: this.form.password,
});
this.$router.replace('/');
}
catch (e) {
this.errors = 'Could not sign you with these credentials.';
console log(e);
}
}
I would stick the second request in .then
await this.$axios.$get(' localhost:8000/sanctum/csrf-cookie ')
.then(() => {
this.$axios.$post('yourPostRoute' ,yourPostData)
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question