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

anthonygore's avatar

Protecting API routes with session guard

I'm using Laravel 5.4 and trying to protect an API route with a session guard but I keep getting 401 Unauthorized errors.

In the frontend app I'm doing my AJAX request like this:

import axios from 'axios';

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

axios.post('/api/do_thing');

In the backend, I have set the API guard to be session:

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

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

And protected my route with the API sesion guard.

Route::post('/api/do_thing', function() { ... })->middleware('auth:api');

By my reckoning, laravel_session cookie gets sent with the AJAX request and should therefore pass the auth check. But I get a 401, any idea why?

Follow up question: what is the downside to using session guard for an API? Why is token/passport preferred?

0 likes
5 replies
anthonygore's avatar

No, this is not a question about Passport, I'm trying to use a session guard on my API routes.

p4rz1val's avatar

Just wanted to add to this question (i know is 1 year old).

Laravel Nova authentication works this way, basically if you don't want to mess with tokens or passport in your SPA or something similar a session based authentication for the API is the best, here's an example of how Laravel Nova handles the authentication:


/*
    |--------------------------------------------------------------------------
    | Nova Route Middleware
    |--------------------------------------------------------------------------
    |
    | These middleware will be assigned to every Nova route, giving you the
    | chance to add your own middleware to this stack or override any of
    | the existing middleware. Or, you can just stick with this stack.
    |
    */
    'middleware' => [
        'web',
        Authenticate::class,
        DispatchServingNovaEvent::class,  // Nova specific middleware
        BootTools::class,  // Nova specific middleware
        //Authorize::class,  // Nova specific middleware
    ],


basically you need the web group middleware + the auth middleware for your session based api authentication to work, so:

'api' => [
        'web',
        \App\Http\Middleware\Authenticate::class
],

Also i encourage everyone (myself included) to learn more about how authentication works in Laravel and different Authentication approaches.

1 like

Please or to participate in this conversation.