'Create session on consuming login with api on laravel

I have an api that has a method to start and I am calling it from a frontend project.

In the front end project I use Guzzle to make the call via post to the api and login, from which I get back a json with the user data and a jwt token.

But when I receive the token as I manage the session, I must create a session and save the token, since the laravel to authenticate I need a model user and have a database, which of course I do not have in this backend because I call the api to log in, which brings a token and user data, then as I manage it from the backend, I'm a little lost there.

            $api = new Api();
            $response = $api->loginapi(['user'=>'[email protected]','password'=>'123']);
            

Because here I could not do Auth::login($user) to generate the session. Because I don't have here the database because the login is done from the api.

There I call the api, of which the answer is the token, but how do I manage it from here, creating a session? saving the token?

thanks for your help.



Solution 1:[1]

With api, you don't usually manage a session. usually, you'd call something like

Auth::attempt([
    'email' => '[email protected]',
    'password' => 'myPassword'
]);

If the credentials are correct, laravel will include a Set-Cookie header in response, and, that is how you authenticate with api. Via an auth cookie. You don't need to do anything else.

Let's show you how:

//AuthController.php
public function login(Request $request) {
    $validatedData = $request->validate([
        'email' => 'required|email',
        'password' => 'required'
    ]);

    if(Auth::attempt($validatedData)){
        return ['success' => 'true'];
    }

    else{
        return ['success' => false, 'message' => 'Email or password Invalid'];
    }
}

public function currentUser (){
    return Auth::user();
}

Now, the APi file

Route::post('/login', ['App\Http\Controllers\AuthController', 'login']);
Route::get('/current_user', ['App\Http\Controllers\AuthController', 'currentUser']);

Now if you make a call to /api/current_user initially, you'll get null response since you're not currently logged in. But once you make request to /api/login and you get a successful response, you are now logged in. Now if you go to /api/current_user, you should see that you're already logged in.

Important ::

If you are using fetch, you need to include credentials if you're using something other than fetch, check out how to use credentials with that library or api

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ronodip Basak