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

meredevelopment's avatar

Allowing session-based Users to access API - is there a nicer / safer way?

I have a Passport protected API as part of a public-facing App, with external parties connecting with Personal Access Tokens. This ideally needs to stay as-is.

'Users' with accounts (plain old username/pass) also login to this App, and need to query some parts of the API with Vue in Views. This is where I'd like help and suggestions please:

At present I have the following sort of setup:

api.php

Route::group(['middleware' => 'auth:api'], function () {
    Route::apiResources(
        [
            'example' => 'API\ExampleController',
            // all the other resources

        ],
        ['except' => ['destroy']]
    );
});

web.php

Route::group(['middleware' => 'auth'], function () {
    Route::resources(
        [
            'example' => 'API\ExampleController',
            // all the other resources
        ],
        ['only' => ['index','show']]
    );
});

And in Views I'm doing stuff like this:

axios.get('/members/'+this.query)
.then(response => {
    // etc
})
.catch(error => {
    // etc
})

This all works fine... but a few questions:

  • Is there a way to not have to list all the Resources/Controllers in both Routes files? Maybe a way to import them from one place? I did attempt to add the EncryptCookies and StartSession middleware to the api group in Kernel.php but no luck, I get not authenticated errors when GETing the data.

  • Is this sort of access to the API via a session safe? I have the appropriate CSRF fields added to the Axios config (as it is out the box these days).

  • Finally, it strikes me that this sort of setup, i.e. having both an API and local users on one App must be quite common? How are others doing it if not this way?

Thanks for reading 👍

0 likes
3 replies
Pciranda's avatar

Add the following middlewares.

// App\Http\Kernel.php
protected $middlewareGroups = [
        'web' => [
               \App\Http\Middleware\EncryptCookies::class,
               \Passport\Http\Middleware\CreateFreshApiToken::class,
        ],
        'api' => [
            'auth:api',
        ],
];

When using EncryptCookies together withCreateFreshApiToken, Laravel will insert an access token into the cookie. This cookie will be sent along with your axios request and will allow access to api routes.

This Passport middleware will attach a laravel_token cookie to your outgoing responses. This cookie contains an encrypted JWT that Passport will use to authenticate API requests from your JavaScript application. Now, you may make requests to your API's application without explicitly passing an access token:  https://laravel.com/docs/5.8/passport#consuming-your-api-with-javascript

1 like

Please or to participate in this conversation.