mardi 18 décembre 2018

Laravel Passport: CreateFreshApiToken in App: Authorization Failed

I'm attempting to install Laravel Passport on Laravel 5.7.18 using PHP 7.2.13.

My application consumes the API within itself using JavaScript (Axios with Vue)

I'm getting a 401 Unauthorized error within the JavaScript web application. I've read the documentation and added CreateFreshApiToken to the web Kernel. The laravel_token cookie is in fact setting itself. However, the oauth tables are clean in the database.

Http/Kernel:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

JavaScript:

axios.get("api/users/" + id).then(({ data }) => {
    this.user = data;
});

Auth.php:

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

        'api' => [
            'driver'   => 'passport',
            'provider' => 'users',
        ],
    ],

Routes (Api.php):

Route::middleware('auth:api')->group(function () {
    Route::resource('users', 'UserController');
    Route::resource('groups', 'GroupController');
    // .. plus more resources
});

Axios Config:

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

var token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
  window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
  console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire