Hi, I'm building a frontend application using Laravel that consumes data from an API.
I need to authenticate users for access to certain views and said authentication is done through the before mentioned API like this: I send a username and password to the API and I either get an error or a session token to use for future authenticated requests.
My first idea is to store said token on Laravel's session and have the authentication guard check for its existence and validated it against and endpoint on the API.
I've tried doing this:
Http/Controllers/LoginController.php
...
public function authenticate(Request $request)
{
$data = ['email' => $request->email, 'password' => $request->password];
$apiUrl = env('API_URL', '');
$response = Http::asForm()->post("$apiUrl/admin/login", $data);
if ($response->status() === 200) {
$apiSession = $response->cookies()->getCookieByName('session')->getValue();
$request->session()->regenerate();
$request->session()->put('token', $apiSession);
return redirect(route('admin'));
}
// Else => Login error handling
...
}
...
routes/web.php :
...
$router->get('/admin', [AdminController::class, 'admin'])->middleware('auth')->name('admin');
...
Http/Middleware/Authenticate.php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
return route('login');
}
}
}
But after login in successfully I get redirected back to the login form.
I thought that the $request->session()->regenerate(); was the call to make so Laravel's default auth logic would see the current session as an authenticated one but I guess not.
Can anyone tell me what am I missing? or if I'm going at it in a wrong way.
Thank you!
P.S.: I've also changed the SESSION_DRIVER environment variable to be cookie.