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

afabris's avatar

Allowing access to API via token and session

I have APIs that can be accessed by 3rd party apps, and APIs that need to be accessed by users. 3rd party apps are on the same server and share the database, so I managed this using in config/auth.php


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

Users however are on the different server, and they need to use token, so in this case I need to use:

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

However I need to use this at the same time. Is there a simple way to accomplish this (Laravel 5.2).

Thanks, Andre

0 likes
3 replies
robrogers3's avatar

I think this is your answer:

https://mattstauffer.com/blog/multiple-authentication-guard-drivers-including-api-in-laravel-5-2/

e.g.

    'api-user' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

then protected your user api with the associated middleware: ->middleware('auth:api-user')

just like the api.php routes:

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

I dont think you need to create your custom auth service provider as you are reusing the token guard.

I do wonder if you need another route defined to use the new guard. as in:

Route::get('money', 'SomeController@index')->middleware('auth'); //web users

Route::get('user-api-money', 'SomeController@index')->middleware('auth:api-user') //api users

??

afabris's avatar
afabris
OP
Best Answer
Level 1

Thanks I tried, but something seems missing. Auth::check() does not work - user is not logged in. If I add guard('auth:api') or any other still does not work.

However, I found the easier solution. routes.php uses web guard, and my api_routes uses api guard. web guard is session and api guard is token.

So I moved APIs that need to use session for authorisation to routes.php and left APIs that need to use token for authorisation in api_routes.php. This works exactly as I need. I hope it will help someone in the future.

amoktar's avatar

what about latest laravel 8 ? this post is 3 years ago

Please or to participate in this conversation.