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

krs's avatar
Level 17

Login via 3rd party app

Hello all!

Via an API call a user should be able to log in to my laravel app, so after some security checks I use

Auth::login($user, true)

with an existing $user and then redirect to the welcome page.

When I auth()->check() after the login, it's successfull, and the browser retrieves the csrf and session cookies.

BUT when I redirect the user after this successful login, the laravel app seems to forget the login and opens the login page again:

 public function authenticateAPIConsumerOI(Request $request)
    {
        //first check bearer validity
        abort_if(!$request->personal_access_token, 403, 'Auth failed #1');
        abort_if(!ForeignAuthBearer::check($request->personal_access_token), 403, 'Auth failed #2');

        //data existence
        abort_if(!$request->email, 403, 'Auth failed #3');
        abort_if(!$request->user_category, 403, 'Auth failed #4');

        //validating
        $data = $request->validate([
            'email' => ['required', 'email'],
            'user_category' => ['required', 'integer'],
        ]);

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

        if (!$user) {

            $user = User::create([
                'email' => $data['email'],
                'password' => bcrypt(Str::random(40)), //random password
                'last' => 'AutoCreate',
                'first' => 'WSH',
                'tenant_id' => $this->connection['tenant_id'],
            ]);
            $tenant_user = TenantUser::create([
                'tenant_id' => $this->connection['tenant_id'],
                'user_id' => $user->id,
                'user_state_id' => $this->connection['user_state_id'],
            ]);

            $user_category_ids = $this->get_user_category_ids($data['user_category']);
            $tenant_user->user_categories()->sync($user_category_ids);

            $this->update_user_details($user, $tenant_user, $data['email'], $data['user_category']);
        } else {

            $tenant_user = TenantUser::query()
                ->where('user_id', $user->id)
                ->where('tenant_id', $this->connection['tenant_id'])
                ->first();

            $this->update_user_details($user, $tenant_user, $data['email'], $data['user_category']);
        }

        Auth::login($user, true);	

        dump(Auth::check());				// says "true"

        return redirect('/');	//after redirect: auth()->check() says "false"
    }

I already tried another routes-group (not via api), where no middleware was enabled, same result...

What I am missing here?

Thanks, Stefan

0 likes
0 replies

Please or to participate in this conversation.