Laravel passport auth through CreateFreshApiToken always returns {“message”:“Unauthenticated.”}

放肆的年华 提交于 2019-12-08 18:23:27

This works for me in a Laravel 5.6 project:

<?php

namespace App\Http\Middleware;

use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class EncryptCookies extends Middleware
{
    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array
     */
    protected static $serialize = true;

    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

Set the property $serialize to true on EncryptCookies middleware.

Source: https://laravel.com/docs/5.6/upgrade#upgrade-5.6.30

Source: Laravel passport consuming api with js not working

After browsing and browsing and browsing..

Turns out the problem comes, indeed, from the cookies not being sent with the request for CORS. I fixed it by adding "withCredentials" to my Ajax call:

window.$.ajax({
    headers: {
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    xhrFields: {
       withCredentials: true
    },
    type: 'GET',
    url: 'https://mywebsite.test/api/testApi',
    success: function (response) {
        console.log(response);
    },
    error: function (xhr) {
        console.error(xhr.responseText);
    }
});

You also need to ensure the headers for your response specify that credentials are accepted:

header('Access-Control-Allow-Credentials: true');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!