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

subpublic's avatar

auth:api problem in Ajax

Hi!

I'm using the artisan make:auth. The session authentication works fine, but the ajax api requests gives me 401 Unauthorized (using Vue). I can see the X-CSRF-TOKEN is set in the header. And if I remove the 'middleware' => ['auth:api'] the $request->header('X-CSRF-TOKEN') is also set.

Any ideas? Or suggestion on how to debug this further?

I'm using Laravel 5.3 with php5.6.

0 likes
11 replies
subpublic's avatar

My api route (in api.php) is

Route::post('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

And in Vue

this.$http.post('/api/user')

If I remove ->middleware('auth:api') the route works fine.

mstnorris's avatar
Level 55

@subpublic Have you added the '\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,' to your Kernel.php file within the 'web' middleware group?

See here

2 likes
subpublic's avatar

Thanks!

I had fooled around a bit too much with passport. When adding that plus setting 'driver' => 'passport' in my ayth.php it started working.

Question, do I really need passport for regular api-token authentication?

2 likes
mstnorris's avatar

Why not? I'm going through the same thing at the moment, I don't need passport other than for my own front-end app, but I may in the future.

jfvoliveira's avatar

Hi there. I'm having the same problem and this is bugging me. Do I have to install Passport (a tool to ease the OAuth Server creation) just so I can use my API via JavaScript?

Shouldn't it be easier? I want to use the API via JS only when I am authenticated. How can I accomplish that?

2 likes
mstnorris's avatar

Yep you can; install passport, and read over the docs mentioned above. :)

subpublic's avatar

@jfvoliveira At last I found out the problem. If you only want to make simple Ajax requests, don't put those urls in the /api. You can just use middleware('web') and respond in json.

1 like
jfvoliveira's avatar

@subpublic I've tried that but if I include the auth middleware (I need it as I need to know what user did what action) I keep getting the TokenMismatchException.

subpublic's avatar

@jfvoliveira The auth middleware works fine for me, as long as I keep the routes in web.php. But I did have some token trouble, but couldn't really understand if it was bacause I had installed the auth:api or if I had moved around to many files. So I set up a brand new Laravel without auth:api and now it works just fine.

lwagenaar's avatar

Instead of using Laravel/Passport I create my own middleware for ajax request :)

1 like

Please or to participate in this conversation.