简体   繁体   中英

Laravel sanctum works in localhost, but returns 401 unauthenticated in live server

This is my 3rd post in a row on this issue, unfortunately I am not getting proper answer. I am developing an authentication system using laravel-sanctum in a laravel-vuejs app. The laravel-sanctum works fine (return user info from "/api/user" api) in the localhost. But when I am deploying in a live server, it returns 401 (unauthenicated) error. I am sharing my header here:

在此处输入图像描述

my.env

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:WvNeYkRnJbXNcttmiAKe1blplUslHWIsRQpvnPt0mxA=
APP_DEBUG=true
APP_URL=https://subdomain.domain.com/


DB_CONNECTION=mysql
DB_HOST=127.0.0.1

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=subdomain.domain.com
SESSION_SECURE_COOKIE=false
SANCTUM_STATIC_DOMAIN=subdomain.domain.com

My sanctum.php

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'subdomain.domain.com')),

'guard' => ['api'],

cors.php

'supports_credentials' => true,

auth.php

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

'guards' => [
    'api' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],

From bootstrap.js

window.axios = require('axios');

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

axios.defaults.withCredentials = true

Code from component (script)

mounted() {
    axios.defaults.headers.common["Authorization"] = `Bearer ${this.token}`;
    axios.get('/api/user').then(response => {
        this.userInfo = response.data
    })
}

I think you should define home url in the blade page you use vue app like this.

<script>
      window.home = "<?php echo your-host-url ?>";
</script>

To make sure the API route is correct you add:

axios.get(window.home + '/api/user').then(response => {
    this.userInfo = response.data
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM