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

AndreBoyle's avatar

Accessing any route in api.php logs out session

I've got a new project and have started created routes in api.php to consume in VUE.

This a latest version (5.8) laravel project with telescope and passport installed. It is otherwise vanilla. Session are set to persist in the database, rather than the default option of file.

Adding routes requiring auth in web.php works just fine and redirects to the login page as required on accessing them while logged out.

However, if I attempt to access any route which has auth:api as it's middleware, the user session is logged out and I get a 401 unauthorized error and redirected to the login page.

On viewing AXIOS requests I can see that the various headers I've used in the past are all being sent as expected and the CSRF token is indeed included, as it is in the HTML header.

This is driving me to distraction so any help would be greatly appreciated as I've spent 6 hours trawling through commonly suggested fixes and have debugged to the best of my ability in Laravel.

Thanks all for anything you can point me to.

0 likes
4 replies
AndreBoyle's avatar

Thanks for that. However, the bootstrap.js which is included in the default setup includes the setup needed to add the necessary headers for Axios. So this should already be including everything, which I can confirm as I can see them being sent in the DevTools in Chrome. Looks like the server is not accepting it.

Another possibility, though I'm less convinced, is that the auth:api endpoints should expect a request which accepts application/json, axios by default does send this but it may be being ignored. If ignored, it redirects the user to the \login path and clears the session. This fits the behaviour but I can't see why it would be triggering it.

AndreBoyle's avatar

Forgot to say is that my understanding from past experience (I can't recall doing anything different) was that Vue/Axios are auto configured to connect without the need for any extra config (generally). Whereas external services connecting, or other apps/sites, would require the full bearer, etc to be configured. I've tested this with Postman and it certainly looks to be the case. But that's for full blown OAUTH style requests.

Inbuilt Vue should just work.

AndreBoyle's avatar

OK folks, I'm daft as I forgot one single line to add to kernel.php

By adding this line below the 'web' auth method it all worked;

\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

This added the API token in the cookie for requests. I was looking at the CSRF token instead of the API endpoint access token.

All it now good and working.

Please or to participate in this conversation.