Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

partabsaifzakir's avatar

Consuming Your API With JavaScript - Issue

I am using Laravel 5.7 with Vuejs, i'm new at this, i just need to secure my data. When i see Laravel passport documentation, i did same but not working, when i use ('auth:api') i can't see my users table and in Postman app it okay that i cannot see my data, i just add this in my Kernal.php.

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

and then i use this constructor in API controller named 'UserController'

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api');
    }
0 likes
23 replies
jekinney's avatar

Check out this tutorial. If you like it I suggest bookmarking it. Will work with 5.7 btw.

I use it pretty much verbatim for all my API projects.

https://medium.com/modulr/create-api-authentication-with-passport-of-laravel-5-6-1dc2d400a7f

Not really sure what CreateFreshApiToken has to do with it (it doesn't).

Also be sure postman is set up correctly. I set up presets like:

My login example:

Route : /api/auth/login

Tests tab (this will set the enviroment variables. NOTE on token, my tokens come back with Bearer already concatinated on, different then tutorial above):

var data = JSON.parse( responseBody );
pm.environment.set("token", data.data.token);
pm.environment.set("expires", data.data.expires);
// any other variables you need set

Create an environment (upper right) with expires and token. Initial values empty.

Make sure you new enviroment is selected

Now back to Headers tab, on the right click Presets and manage presets:

I create two, first one I call basic then click "bulk-edit":

Accept:application/json
Content-Type:application/json

the second one I call basic w/auth and once again click "bulk-edit":

Content-Type:application/json
Accept:application/json
Authorization:{{token}}

The token in {{ }} is the enviroment variable and is set automaticly when you "login"

Hope that helps!

jekinney's avatar

@partabsaifzakir

You obviously skipped a step somewhere.

If you are using postman, if you are hitting the middleware and not authenticated you should be getting an 501 code.

For first code section, you put middleware in web, you should be in API.

Check your config/auth and set to passport?

If all else fails try

 Route::prefix('blog')->namespace('Blog')->group( function () {

    Route::prefix('category')->group( function() {
        Route::get('/list/full', 'CategoryController@full')->middleware(['auth:api', 'permission:blog-categories,blog-articles']);

using the middleware in your API routes file (notice the array syntax) don' t worry about permissions that is a custome middleware on app I am working on now).

partabsaifzakir's avatar

@jekinney mate let me clear, i have a table of Users in my application, fist of all i installed passport via composer,

composer require laravel/passport

then i export the default migrations using,

php artisan vendor:publish --tag=passport-migrations

then i migrate using,

php artisan migrate

then i install passport using,

php artisan passport:install

then i import Laravel\Passport\HasApiToken in my User model

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

then i call Passport::routes method within the boot method of my AuthServiceProvider.

<?php

namespace App\Providers;

use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}

then, in my config/auth.php configuration file, i set the driver option of the api authentication guard to passport.

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

thats how i installed passport, then in Laravel Passport documentation down below in #Consuming Your API With JavaScript.

i add the CreateFreshApiToken middleware to my web middleware group in my app/Http/Kernel.php file:

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

then i add __constructor in my UserController:

class UserController extends Controller
{
        /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api');
    }

when i do this and refresh my application, i see no users in my application, and in developer tool i get a error of 401 Unauthorized and when i remove this __constructor i can see my users.

You can also see these tutorials i'm doing just like this, please help me i'm stuck in this,

Part 1: https://www.youtube.com/watch?v=gRbuInSwU9U&index=28&list=PLB4AdipoHpxaHDLIaMdtro1eXnQtl_UvE

Part 2: https://www.youtube.com/watch?v=TVmUW-8-UN4&index=29&list=PLB4AdipoHpxaHDLIaMdtro1eXnQtl_UvE

D9705996's avatar

Have you followed the Consuming your own API document right to the bottom

When using this method of authentication, the default Laravel JavaScript scaffolding instructs Axios to always send the X-CSRF-TOKEN and X-Requested-With headers. However, you should be sure to include your CSRF token in a HTML meta tag:

If you follow the link it tells you to add

<meta name="csrf-token" content="{{ csrf_token() }}">

You should add this to you layout's <head> section so it appears in all pages.

partabsaifzakir's avatar

@D9705996 Yes! i'm using this in my layout master.blade.php & app.blade.php. i'm using Vue components, In my Components file i have User.vue do i have to use this :

<meta name="csrf-token" content="{{ csrf_token() }}">

in User.vue file also....?

partabsaifzakir's avatar

@D9705996 @jekinney

in the documentation this is written....

When using this method of authentication, the default Laravel JavaScript scaffolding instructs Axios to always send the X-CSRF-TOKEN and X-Requested-With headers. However, you should be sure to include your CSRF token in a HTML meta tag:

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
};

If you are using a different JavaScript framework, you should make sure it is configured to send the X-CSRF-TOKEN and X-Requested-With headers with every outgoing request.

where should i use this window.axios part...?

Cronix's avatar

If you haven't removed anything laravel provides out of the box, and compiled the assets with npm run dev, then it's already done for axios and should be in app.js. Are you loading that file?

partabsaifzakir's avatar

@Cronix I didn't find any import of axios in app.js.... should i have to import it like this .....???

import axios from 'axios'
window.axios = axios;
Cronix's avatar

I didn't find any import of axios in app.js

It's in /resources/js/bootstrap.js, not /resources/js/app.js. What I was talking about was the compiled app.js, which is in /public/app.js if you used the defaults

The default packages laravel installs are here: https://github.com/laravel/laravel/blob/master/package.json

The default settings are here: https://github.com/laravel/laravel/blob/master/resources/js/bootstrap.js

which has

window.axios = require('axios');

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

The rest of the app is in app.js.

When you run npm run dev, it installs and compiles them into /public/app.js, which you link to in your app.

partabsaifzakir's avatar

@Cronix

okay than what ...? do i have to change some settings or what, i did same as this buddy show me in this tutorials:

Part 1: https://www.youtube.com/watch?v=gRbuInSwU9U&index=28&list=PLB4AdipoHpxaHDLIaMdtro1eXnQtl_UvE

Part 2: https://www.youtube.com/watch?v=TVmUW-8-UN4&index=29&list=PLB4AdipoHpxaHDLIaMdtro1eXnQtl_UvE

but everytime i refresh my page i get this error in my console:

app.js:18775 GET http://localhost:8000/api/user 401 (Unauthorized)
dispatchXhrRequest  @   app.js:18775
xhrAdapter  @   app.js:18609
dispatchRequest @   app.js:52626
Promise.then (async)        
request @   app.js:52082
Axios.(anonymous function)  @   app.js:52092
wrap    @   app.js:18398
loadUsers   @   app.js:72318
mounted @   app.js:72341
callHook    @   app.js:55748
insert  @   app.js:56985
invokeInsertHook    @   app.js:58787
patch   @   app.js:59006
Vue._update @   app.js:55487
updateComponent @   app.js:55615
get @   app.js:55969
Watcher @   app.js:55958
mountComponent  @   app.js:55622
Vue.$mount  @   app.js:61367
Vue.$mount  @   app.js:63766
Vue._init   @   app.js:57467
Vue @   app.js:57556
(anonymous) @   app.js:30797
__webpack_require__ @   app.js:20
Object.defineProperty.value @   app.js:30692
__webpack_require__ @   app.js:20
(anonymous) @   app.js:63
(anonymous) @   app.js:66
app.js:18800 Uncaught (in promise) Error: Request failed with status code 401
    at createError (app.js:18800)
    at settle (app.js:52154)
    at XMLHttpRequest.handleLoad (app.js:18674)
createError @ app.js:18800
settle @ app.js:52154
handleLoad @ app.js:18674
Promise.then (async)
loadUsers @ app.js:72318
mounted @ app.js:72341
callHook @ app.js:55748
insert @ app.js:56985
invokeInsertHook @ app.js:58787
patch @ app.js:59006
Vue._update @ app.js:55487
updateComponent @ app.js:55615
get @ app.js:55969
Watcher @ app.js:55958
mountComponent @ app.js:55622
Vue.$mount @ app.js:61367
Vue.$mount @ app.js:63766
Vue._init @ app.js:57467
Vue @ app.js:57556
(anonymous) @ app.js:30797
__webpack_require__ @ app.js:20
Object.defineProperty.value @ app.js:30692
__webpack_require__ @ app.js:20
(anonymous) @ app.js:63
(anonymous) @ app.js:66

and in my Coockies i get this:

Request Cookies 
        
XSRF-TOKEN

eyJpdiI6IllTMXlWS0psa2FJNFVUWFFrVW9TVUE9PSIsInZhbHVlIjoiWjkySzNGcVBIV1RGNmVSblhkTjRHMG9lS1F5WU0yd0hPbGhVemhyRitLdG1TdERtZDFmTXl2U0x5YjVSelJnRSIsIm1hYyI6ImIyOTc1NTJhM2Y0M2FmYzE5NDQ5ZWQ1ZjA4ZmE4NGI4ZWY4ODkwYTVmOWY4ODFlZjgwNGY3OTg1M2U3ZjNhYzMifQ%3D%3D

            
laravel_session

eyJpdiI6ImM3Y0IxZ3ZhUUc4NjRFM29kd3hMSGc9PSIsInZhbHVlIjoiU1pFSVJxZlN2OTVwM0F2Nmp3SnZzQ1NZWFJJUEgyM0hpdEdFcHpVdSt3bEhhMVNrdVwvQjZod2RBc1dlVm1FcjkiLCJtYWMiOiI1YTU5ZDk3NTUxZDk5Mzc1ZGQ3OWUxMWY5NDU3NjE2MzkzYzY3ZDJlM2Q1M2VmNDAwMTFhNWI5NWU4MGMzMDNiIn0%3D          

laravel_token

eyJpdiI6Ik1XRVwvc2V4dFNGTzBoZEVxdEFSR1p3PT0iLCJ2YWx1ZSI6IkY2MUduaTJEWDRcLzd0RmFMZFduOVRmRlRxVmpFaGEzZ0xDa1FqcU5XM2ZmVVIyd1ZLTWtcL0VIU2I4ckVWTkVcL2NVXC82dE5xcTNGaDRcLytmT1lPb2NcLzUxbHRFVENvZnh6QjBnaVM1XC96R0dHdWM2REVlXC81bUVDTldVRmRheDM1eGxKdDV4SjJGUjZFMW5XSEdobExRUEMzWHcyWFFibkRmSUtuekVmUGxWSmN2cUxHdldPc3lQQjZNRzY2ZjdNZ3B3MWxrRlwvN1ppRkprblwvMWNkbFpudytmeHlITDVOR0R1ekhrN1BWd0hpUEMxY1AxaWN4VDJuREV6ZkR5WFpvOHhXIiwibWFjIjoiZGZhOTliZmI0MTE5MDI2ODZhYzQ1YzA5NDkxNDU3ZTU1NzQ1YThlYzU1ZTEwYmZmZjFmNWQ1MzliZjNlNGVmMiJ9            

Cronix's avatar

I'm sorry, but I don't want to watch a couple videos to see what you're doing.

The error doesn't mention anything about a csrf token. It mentions being unauthorized.

Have you logged into your app before hitting whatever is causing this error?

Or maybe you are, but the policy is rejecting you?

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
];
partabsaifzakir's avatar

@Cronix:

my application is working fine when i remove this __constructor in my User model.

class UserController extends Controller
{
        /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api');
    }

but in Postman when i send get request of api/user it shows me all data, this is not ok.

Cronix's avatar

Try commenting out the policy.

//protected $policies = [
//    'App\Model' => 'App\Policies\ModelPolicy',
//];

and try again. Have you actually created that policy?

How are you sending your requests to the api? Are you using the Vue components or how are you doing it?

Cronix's avatar

Ok, and the rest of what I said? Did you comment out the policy and try again? Did you actually make a "ModelPolicy" policy?

Cronix's avatar

AND NO! I DIDN'T CREATED ANY POLICY....

Then did you remove it like I suggested? If it doesn't exist, then why do you have it?

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
];

Policies will allow/deny the request depending on if it passes/fails the policy check, which sounds like what could be happening here since your getting 401 Unauthorized. Policies authorize you, which is different from authenticating. https://laravel.com/docs/5.7/authorization

partabsaifzakir's avatar

@Cronix ,

In my AuthServiceProvider i have this Policy but i didn't make it, it's already their,

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];
partabsaifzakir's avatar

@Cronix ,

Yes i comment this policy

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    // protected $policies = [
    //     'App\Model' => 'App\Policies\ModelPolicy',
    // ];

still i get the error 401 unauthorized, can't see my Users table, only see my Users table when i remove __constructor

partabsaifzakir's avatar
Level 1

@D9705996 @jekinney and specially you @Cronix,

it's been 18 hours, i stuck in this issue, i just did php artisan config:cache and it worked, i need to cry ....... Thank You so much all of you, you gave your precious time thinking for my issue...

3 likes
Cronix's avatar

I'm glad you got it resolved. Those are fun things to discover lol. If this is a dev environment, I wouldn't cache the config though or you'll run into this sort of things. You should really only cache the config (and routes!) when in production. You probably just needed to php artisan cache:clear

1 like
travis.elkins's avatar

I was stuck for about 30 minutes and, thanks to your post, probably saved even more than 18 hours...! Thanks for following up with your discovery. It certainly helped me out. :-)

Please or to participate in this conversation.