1
votes

Hello I amm trying to secure API with laravel passport, but always throws me 401 unauthorized. where am i making a mistake? Any help? Thank you.

I added into User.php HasApiTokens,

and uncomment 'App\Model' => 'App\Policies\ModelPolicy' and added to boot Passport:routes() in AutServiceProvider.php,

in

auth.php 'api' => [
            'driver' => 'passport',]

in RegisterController.php

 protected function create(array $data)
    {

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
        $token = $user->createToken('API Token')->accessToken;
        return $user;
    }

in bootstrap.js

const token = '3acdc8cddb433947ea7cc51de909fdc50dcdf601ac521ac37ff1b3ee3a61e47e2111d297a07e147e'

window.axios = require('axios');
window.axios.defaults.withCredentials = true;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

in Posts.vue axios

mounted() {
        axios.get('/public/api/posts').then(response=>{
            this.data =response.data
        })
    },
3

3 Answers

0
votes

If you don't need to provide oauth2 you might want to look at Laravel Sanctum which is more light-weight and easier to set-up (https://laravel.com/docs/8.x/passport#passport-or-sanctum).

But if you really need passport, first thing to check is if you followed every step in Passport's installation instructions (https://laravel.com/docs/8.x/passport#installation) such as php artisan passport:install

0
votes

I think you still need x-csrf-token in your headers.common

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

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

May be this can be the late answer. but after clearing my caches the token now work like a charm.

php artisan optimize:clear

Helps me to fix my issues. Also you may give this a try

I had find out that after changing the auth.php file in the configuration to instruct api routes to use the right settings Laravel had already cached difference values this become my tough when trying to clear those caches