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

glaucon's avatar

Request for Assistance in Implementing Cross-Platform Session Management with Laravel Fortify and Sanctum

Problem Description:

I have developed an application using Laravel, which includes both a website and mobile apps built with Flutter. Currently, I am able to manage browser sessions effectively using the Fortify package on the website. However, I am facing challenges when it comes to managing web sessions alongside mobile sessions. My goal is to display all active user sessions on both the web and mobile platforms, allowing users to log out from all sessions except the current one.

Here is my current api login method:

public function login(Request $request) { try { $credentials = $request->validate([ 'email' => 'required|email', 'password' => 'required|string|min:6', 'device_name' => 'sometimes|max:100', ]); } catch (ValidationException $errors) { return $this->validationErrorResponse($errors); }

    $user = User::where('email', $credentials['email'])->first();

    if (!$user || !Hash::check($credentials['password'], $user->password)) {
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }

    // Remove last authentication token for this device
    if ($request->has('device_name')) {
        $this->removeLastToken($request->device_name, $user);
    }

    $token =  $user->createToken($request->has('device_name') ? $request->device_name : "api-token")->plainTextToken;

    // Prepare user data for response
    $data = $this->prepareData($user, $token);

    return response()->json([
        'response_code' => '200',
        'response_message' => 'success',
        'user' => $data
    ], 200);
}

private function removeLastToken(string $device_name, User $user)
{
    $lastToken = DB::table('personal_access_tokens')
        ->where('name', $device_name)
        ->where('tokenable_id', $user->id)
        ->first();

    if ($lastToken) {
        $lastTokenId = $lastToken->id;
        $user->tokens()->where('id', $lastTokenId)->delete();
    }
}

I'm using Postman to send login requests, receiving a token in response, and then using this token for other API requests protected by the auth:sanctum middleware. However, I'm facing an issue with the sessions table. When I send a GET request with the {Accept: application/json, Referer: localhost:8000} header and the correct bearer token, I can see the correct user session in the sessions table, even from Postman. But as soon as I send a POST request with the same header and the correct bearer token, I get a CSRF-TOKEN mismatch error. And when I send a POST request with just {Accept: application/json} and the correct bearer token, the user_id in the sessions table becomes null, making it seem like the session doesn't exist. The problem is that the session should not reset on each POST request.

Configuration Details:

.env file:

SESSION_DRIVER=database SANCTUM_STATEFUL_DOMAINS=127.0.0.1:8000,localhost,localhost:8000 SESSION_SECURE_COOKIE=false SESSION_DOMAIN=127.0.0.1:8000

app\Http\Kernel.php:

    'api' => [
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        // \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        'throttle:api',
        // \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        // \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

config\cors.php:

0 likes
0 replies

Please or to participate in this conversation.