make sure you use web.php for your front end requests. These are not API requests.
How to use Cookies based session authentication (Sanctum from Laravel 11) with Vue3
I have two platforms: one built with pure PHP and session-based authentication, and the other using Laravel 11 and Vue 3. We have the authentication logic implemented on the first platform, and I'm working to sync the user's authentication status across both platforms. I transfer data from the first system to the second using a JWT token. On the Laravel side, I validate this token, authenticate the user, and save their data in session variables. I need to use this data for the subsequent frontend request, but I received an "401 Unauthorized" error. Here's my codes: 1- First platform redirect function:
/**
* Social Media App login request
* @return void
*/
public function actionSocialMediaLogin(): void
{
$token = AuthService::buildJWT(SOCIAL_MEDIA_REDIRECT_URL);
if ($token) {
header('location:' . SOCIAL_MEDIA_REDIRECT_URL . '?token=' . $token);
exit;
} else {
$this->render('dashboard/auth/error', [
'error' => "Failed, refresh this page"
]);
}
}
2- Laravel Web Route to validate the token:
Route::get('/login-check', function () {
return redirect('/');
})->middleware('validateToken');
3- ValidateToken Middleware
public function handle(Request $request, Closure $next): Response
{
$token = $request->query('token');
if (!$token) {
return redirect('login')->with('error', 'Token not provided');
}
try {
$decoded = JWT::decode($token, new Key(env('JWT_SECRET_KEY'), 'HS256'));
// Store user data in session or auth context
session(['userId' => $decoded->user_id, 'organizationId' => $decoded->organization_id, 'roleId' => $decoded->role_id]);
Auth::loginUsingId($decoded->user_id);
} catch (\Exception $e) {
return redirect('login')->with('error', 'Invalid token');
}
return $next($request);
}
4- Front-end function to get the user data
const getUserData = async () => {
await axios.get('/sanctum/csrf-cookie')
return await axios
.get("/user-data", { withCredentials: true, withXSRFToken: true })
.then((response) => {
if (response.data.status == "success") {
const newUser = response.data.user;
const newOrganization = response.data.organization;
const newRole = response.data.role;
// Check if data is not empty
if (!newUser || !newOrganization || !newRole) {
return false;
}
// Save to pinia store
user.value = newUser;
organization.value = newOrganization;
role.value = newRole;
roleGroup.value =
newRole.Name.split(" ")[0]
.toLowerCase()
.replace("_", " ") || "";
return true;
}
return false;
});
};
5- API Route to get the user data
Route::get("user-data", "getUserData")->middleware("auth:sanctum");
Note: The ValidateToken middleware functioned correctly, and I was able to return the session variables, but they were missing after the API request.
I expected after calling API to be authenticated as the authentication process ran okay on the first step.
Please or to participate in this conversation.