Search code examples
laravellaravel-9laravel-authenticationlaravel-breeze

Laravel 9 with breeze, how to make login user from external JavaScript?


I am trying to build API for login into my Laravel site from an external JavaScript.
I used Breeze starter kit for Authentication.

In the JavaScript, first it calls an API for getting login_token, then make a request to login with the token. (Yes, I am not using the token for header, using it as parameter to get User instance.)

So, my api controller, I did this.

 public function setLogin(Request $request)
    {
        $validateResult = $this->authValidate($request);
        if (!empty($validateResult)) return response()->json($validateResult, 401);

        $instance = \Laravel\Sanctum\PersonalAccessToken::findToken($request->login_token);
        if (empty($instance)) {
            return response()
                ->json(['code' => '0', 'msg' => 'failed'], 401);
        }
        
        $user = User::where('id', $instance->tokenable_id)->firstOrFail();
        Auth::login($user);
        // $request->session()->regenerate();

        return response()
            ->json(['code' => '1', 'msg' => 'Hi '.$user->mem_id.', welcome']);
    }

On the JS console, I get code 1 with the success message with currect mem_id.
But on the Laravel side, nothing changed.

What should I do?
$request->session()->regenerate() doesn't make any differences, so I commented the line.
What did I miss?


Solution

  • Okay, I found out what was wrong.

    1. I should pass the given token from Laravel to set login. Not the phrase I made. My mistake was trying to use the phrase for both(getting/setting) as header key.
    2. Because my server environment is unusual case, I can't connect my website through 'localhost' or '127.0.0.1'. So I have to set the variable "SANCTUM_STATEFUL_DOMAINS" in .env file.

    Basically, modifying those two things solved the problem.