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

catholicmatch's avatar

Can separate Auth + Session combinations coexist?

I'll do my best to not to be wordy!

The existing site (running Laravel 5.3) uses cookie-based authentication with database-stored sessions. The current project is to create an app using Passport (password grant) authentication to consume an API.

Although I know APIs are typically session-less, some of the existing endpoints provide the same JSON data via AJAX that the API would require -- but rely heavily on session data. It would significantly reduce the workload if the API could use the same controllers, but this would require that an authenticated API request have a session.

I won't go though everything that I tried and failed, but what I have working makes me uncomfortable, mostly because I obviously am failing in my understanding of how the SessionManager handles multiple simultaneous drivers. What HAS worked is API middleware (after authentication middleware) that initializes an eloquent model for a database using the JWT token id in place of what would typically be a session cookie. I'm sure this is morally abhorrent, but it allows global session() use.

public function handle($request, Closure $next)
{
# initalize pre-request
    $session = \App\Models\ApiSession::initSession( auth('api')->user() );
    app()['session'] = $session;

    $response = $next($request);

# post-request store
    $session->save();

    return $response;
}

I'd rather do it right if someone can provide some direction!

0 likes
1 reply
bobbybouwmann's avatar

So I'm not sure what you're after here, but I think you current approach is incorrect. Like you said an API should be stateless. All alarms goes off if you continue this route. I would say to the extra work to make it a stateless API. Even if that means some duplicated code in the end. You will feel the benefits from this later! Right now you're hacking everything together in your middleware.. I don't think you should be doing this at all!

I think you can get away by simply adding the session middleware to those routes and it should work, but still I would say separate the API from the application!

Please or to participate in this conversation.