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

matthes's avatar

Laravel Sanctum SPA + Socialite (Authentik)

Hey folks,

I'm going to need some assistance with my Laravel SPA app. The app is setup with Sanctum and a Vue frontend with axios - everything is working great with local users. I can login and all API calls are automatically authenticated through Sanctum.

Now I'm trying to allow users to login with OAuth2 through Authentik. In the web routes I have the usual redirect method:

public function redirect()
{
    return Socialite::driver('authentik')->redirect();
}

And the callback method:

public function callback(Request $request)
{
    $user = Socialite::driver('authentik')->stateless()->user();

    $user = User::updateOrCreate([
        'authentik_id' => $user->id,
    ], [
        'name' => $user->name,
        'email' => $user->email,
        'authentik_token' => $user->token,
        'authentik_refresh_token' => $user->refreshToken,
    ]);

    Auth::login($user);
    $request->session()->regenerate();

    // dd(Auth::user());

    return redirect('/');
}

After the redirect, the user is successfully created and when uncommenting the line dd(Auth::user()), the correct user is returned. Therefore my assumption is, that the login procedure worked.

My problem though is that the very next API call will return null when calling Auth::user(). Looks like the session is just gone. I can still see a session ID being sent to the API though.

There are two differences I can spot but I'm not sure what to do with it.

  1. When using local users, I'm authenticating the user with Auth::attempt($credentials) instead auf Auth::login($user)
  2. The authentication route for local users is within the API routes, the authentication route for Socialite is in the web routes.

Anyone got a hint for me?

0 likes
1 reply
matthes's avatar

I think I figured it out. My issues was having \Illuminate\Session\Middleware\StartSession::class in the $middlewareGroups array in the kernel AND having it in the $middleware array. Removing it from the former resolved my issue.

Please or to participate in this conversation.