php - How to see if you are logged in laravel api ← (PHP, Laravel)

Theres Auth::check and auth('api')->check() but if you use a token, and you go to the console, application tab and click cookies and blow away the laravel session, then try and make an api call using auth:api as the middleware with token based check, you can still do api requests.

I am unsure how to NOT allow you to do this, I attempted to create a middleware that would check if you are physically logged into the system in order to do api calls, regardless of the fact that you have a token but it seems to state that Auth::check is true, and the auth()->user() returns a user when that middleware in question is hit when doing api calls while you have no session.

For example heres the middleware:

<?php

....

class IsCharacterLoggedInMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        dump(auth()->user(), auth('api')->check(), Auth::check()); // Returns: user object, true, true - even though I have no session.
        if (!Auth::check()) {
            dd(auth()->user());
            return event(new RefreshUserScreenEvent(auth()->user()));
        }

        return $next($request);
    }
}

If I then use this in Route::middleware([...]) around an api call, go to the console, application -> cookies, blow away laravel_session and then hit the api end point, the api request succeeds.

But if I then refresh, I am back on the login page.

In the config section I use:

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

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => true,
        'input_key' => 'private_game_key',
        'storage_key' => 'game_key',
    ],
],

As you can see for api I use tokens. But I also want to use session to say: Ok you have a vlid key, but you are not physically logged in.

How do I check for a valid session when making an api call? All my google searches say to use: Auth::check() But is that right am I doing something wrong?

Answer



Solution:

Token auth is meant not having to keep sessions alive,
but one can still use the session driver, when required:

'api' => [
    'driver' => 'session',
    ...
],

Or alternatively, use web routes with the session driver.

Source